Flutter/Dart:如何获取键等于的列表值
Flutter/Dart: How to get list value where key equals
我不确定为什么我很难找到这个问题的答案,但我有一个列表,我需要从键匹配特定条件的地方获取值。钥匙都是独一无二的。在下面的示例中,我想获得 color
,其中 name
等于 "headache"。结果应为“4294930176”。
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
我得到的错误:Class“_InternalLinkedHashMap”没有实例getter'name'。有什么建议吗?
编辑:
以下是我将数据添加到列表的方式,其中 userDocuments 取自 Firestore 集合:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
我想,我明白问题出在哪里了。您犯了一个小错误,那就是您试图将 Map
元素称为 object
值。
HashMap 元素不能被称为f.name
,它必须被称为f['name']
。因此,以您的代码作为参考,执行此操作,您就可以开始了。
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
检查一下,如果对您有帮助,请告诉我,我相信会的:)
我不确定为什么我很难找到这个问题的答案,但我有一个列表,我需要从键匹配特定条件的地方获取值。钥匙都是独一无二的。在下面的示例中,我想获得 color
,其中 name
等于 "headache"。结果应为“4294930176”。
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
我得到的错误:Class“_InternalLinkedHashMap”没有实例getter'name'。有什么建议吗?
编辑: 以下是我将数据添加到列表的方式,其中 userDocuments 取自 Firestore 集合:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
我想,我明白问题出在哪里了。您犯了一个小错误,那就是您试图将 Map
元素称为 object
值。
HashMap 元素不能被称为f.name
,它必须被称为f['name']
。因此,以您的代码作为参考,执行此操作,您就可以开始了。
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
检查一下,如果对您有帮助,请告诉我,我相信会的:)