【问题标题】:Get value from Instance in Flutter从 Flutter 中的 Instance 获取价值
【发布时间】:2020-06-01 13:33:27
【问题描述】:

我正在使用 Provider 模式在列表上发出搜索请求。

List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];

而Query是这样的

List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();

当我传递值 Apple 时,我期望得到的结果是 iphone

但是我得到的屏幕结果是[instance of ‘Device’] 当我这样编码时

child: Text('${deviceData.getDevice('Apple')}'

我知道我应该使用 two 来使用某种键...但我不知道 :-(

【问题讨论】:

  • Device 对象覆盖toString() 方法

标签: flutter dart flutter-provider


【解决方案1】:

通过 [Instance of 'Device'] 的外观,该函数似乎正在返回一个列表,因此最好检查该列表是否为空。如果不为空,则仍需要选择其中一个元素。我猜它应该是 Text('${chordData.chordExpand('Apple')[0].two}') 以防列表不为空。

总而言之,当列表为空时,使用这样的东西来处理情况

// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists

return <Your Widget>(
.....
Text(textToWrite),
.....
);

【讨论】:

  • 谢谢。当我做.map((device) =&gt; device.two) 时它起作用了。如果列表为空,我将添加一个空检查功能。
【解决方案2】:

你序列化了错误的对象。

你所做的最终类似于:

Text(Device(one: 'Apple', two: 'iphone').toString());

但你不想做Device.toString()。您想要的是将Device.two 传递给您的Text

因此,您的最终结果是:

Text('${chordData.chordExpand('Apple').two}')

【讨论】:

  • 如你所说,我想将Device.two 值传递给屏幕上的Text。但是上面的查询返回List&lt;Device&gt; 值并返回The getter two isn't defined for the class 'List&lt;Device&gt;'. 错误。当我将查询类型更改为 Text ... The getter two isn't defined for the class 'String 时出现同样的错误
  • 然后做一个.map((device) =&gt; device.two)
  • 您好,您能帮我解决这个问题吗? stackoverflow.com/questions/60386200/…
猜你喜欢
  • 2021-07-22
  • 2022-10-24
  • 2021-03-08
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2020-07-30
  • 2021-06-28
  • 2021-02-12
相关资源
最近更新 更多