从 Flutter 中的 Instance 中获取价值

Get value from Instance in Flutter

我正在使用提供商模式在列表中发出搜索请求。

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

而查询是这样的

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

当我传递值 Apple.

时,我期望得到的结果是 iphone

但是我在屏幕上得到的结果是[‘Device’的实例] 当我这样编码时

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

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

你序列化了错误的对象。

你所做的最终类似于:

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

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

因此您的最终结果是:

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

从 [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),
.....
);