Joh*_*hly 3 list key-value dart flutter
我不知道为什么我很难找到答案,但我有一个列表,我需要从键匹配特定条件的地方获取值。钥匙都是独一无二的。在下面的例子中,我想要得到的color,其中name等于“头疼”。结果应该是“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);
Run Code Online (Sandbox Code Playgroud)
我得到的错误:“_InternalLinkedHashMap”类没有实例获取器“名称”。有什么建议?
编辑:这是我将数据添加到列表中的方式,其中 userDocuments 取自 Firestore 集合:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
Run Code Online (Sandbox Code Playgroud)
我想,我明白了问题所在。你犯了一个小错误,那就是,你试图将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);
Run Code Online (Sandbox Code Playgroud)
检查一下,如果这对您有帮助,请告诉我,我相信它会:)