Flutter / Dart:如何在键等于的情况下获取列表值

问题描述 投票:0回答:1

我不确定为什么我很难找到答案,但是我有一个列表,我需要从键与特定条件匹配的地方获取值。按键都是唯一的。在下面的示例中,我想获取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);

我得到的错误:类'_InternalLinkedHashMap'没有实例获取器'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);
}
list flutter dart key-value
1个回答
1
投票
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);

检查一下,让我知道是否对您有帮助,我相信它会:)

© www.soinside.com 2019 - 2024. All rights reserved.