对象查询并删除飞镖中的括号,颤动 [英] object query and remove parentheses in dart, flutter

查看:73
本文介绍了对象查询并删除飞镖中的括号,颤动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好?我正在使用flutter提供程序模式构建应用程序.然后我创建了一个查询对象内部值的过程.我的模型飞镖文件中也有数据.

Hello? I'm building an app using the flutter provider pattern. And I created a process to query the values ​​inside the object. I also have data in my model dart file.

检查下面的代码.

List<Device> _devices = [
    Device(one: 'apple', two: 'iphone'),
    Device(one: 'samsung', two: 'galaxy')
];


String Query(String value) {
    return _media.where((medium) => medium.one == value)
                    .map((medium) => (medium.two)).toString();

Query("apple")

因此,当我调用该函数时,我希望返回iphone.但是结果在(iphne)中.其实我知道为什么.毕竟,返回的数据是List<Device>类型.但是我想要的是通过仅返回查询列表中的第一个值来删除括号(这意味着仅查询列表,而不是完整列表).换句话说,我想接收iphone,而不是(iphone).当前,我正在使用substring删除第一个和最后一个词,这似乎有一些限制.有什么办法可以消除该逻辑中的括号?

So, when I call that function, I expect iphone to be returned. But the results come in (iphne). Actually I know why. After all, the data returned is a List<Device> type. But what I want is to remove the parentheses by returning only the first value in the queried list(meaning only queried list, not the full list). In other words, I want to receive iphone, not (iphone). Currently, I am using substring removing the first and the final word, which seems to have some limitations. Is there any way to remove parentheses in that logic?

推荐答案

由于在列表中调用.toString(),因此带有括号:

You have parentheses because you're calling .toString() on a list:

return _media.where((medium) => medium.one == value)
  .map((medium) => (medium.two))
  .toString();

要仅返回.two或第一个找到的对象,只需执行以下操作:

To return just .two or the first found object, you just have to do:

return _media.firstWhere(
  (medium) => medium.one == value, orElse: () => null)?.two;

这将返回第一个找到的对象的.two的值,或者如果找不到任何内容,则返回null的值.

That will return the value of .two of the first found object or null if nothing found.

文档: Iterable.firstWhere()

这篇关于对象查询并删除飞镖中的括号,颤动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆