【问题标题】:Flutter/Dart: How to get list value where key equalsFlutter/Dart:如何获取键等于的列表值
【发布时间】:2020-10-03 13:17:24
【问题描述】:

我不知道为什么我很难找到答案,但我有一个列表,我需要从键匹配某些条件的位置获取值。键都是唯一的。在下面的示例中,我想得到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”没有实例获取器“名称”。有什么建议吗?

编辑: 以下是我将数据添加到列表的方式,其中 userDocuments 取自 Firestore 集合:

for (int i = 0; i < userDocument.length; i++) {
  var trendColorMap = {
     'name': userDocument[i]['name'],
     'color': userDocument[i]['color'].toString(),
  };
  trendsList.add(trendColorMap);
}

【问题讨论】:

  • 只是为了检查,如果你没有这样做[{'name': 'fatigue', 'color': 4284513675}, {'name': 'headache', 'color': 4294930176}],你能让你的字典看起来像这样吗?然后试试,让我知道?
  • 我刚刚添加了代码以及如何将数据添加到我的列表中。也许你可以告诉我如何正确转换它? @Alok
  • 嘿,我已经回答了你的问题,请查看并告诉我
  • 这可能是一个错字,但您必须在 '" 中写入 keys 和 values。所以正如@Alok 所写,你用过他的名单吗?
  • 嘿@SeriForte,他又犯了一个错误,以错误的方式调用key 来获得价值,我已经展示了正确的方式。无论如何感谢您的支持:)

标签: list flutter dart key-value


【解决方案1】:

我想,我知道问题所在了。你犯了一个小错误,那就是,你试图将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);

检查一下,如果这对你有帮助,请告诉我,我相信它会:)

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2021-06-10
    • 1970-01-01
    • 2019-11-21
    • 2021-11-23
    • 2021-07-16
    • 2012-01-22
    • 2020-10-28
    • 2019-02-02
    相关资源
    最近更新 更多