【问题标题】:how to get values of the some keys in Array of Dictionary in Dart Flutter?如何在 Dart Flutter 的字典数组中获取某些键的值?
【发布时间】:2021-07-16 13:49:19
【问题描述】:

我有一个字典数组,其中字典包含许多键值,我只希望一个键值在一个数组中我不想循环使用 for 循环抛出它我想要一些映射但我不知道为什么它会告诉我错误

这里有一个例子

static final myDictionary = [
{
  "id": 1,
  "name": "Alex",
  "field_of_work": "HR",
  "description": ""
},
{
  "id": 2,
  "name": "Jack",
  "field_of_work": "CEO",
  "description": ""
},
{
  "id": 3,
  "name": "Eric",
  "field_of_work": "Worker",
  "description": ""
},
{
  "id": 4,
  "name": "Sam",
  "field_of_work": "Computer",
  "description": ""
},
{"id": 5, "name": "Michael", "field_of_work": "Others", "description": ""}
];

我希望我的清单是这样的

['Alex','Jack','Eric','Sam','Michael']

所以这是我写的但不起作用的代码(实际上不编译)

myDictionary.asMap().values['name'].toList()

这是错误

The operator '[]' isn't defined for the type 'Iterable<Map<String, Object>>'.

尝试定义运算符'[]'

【问题讨论】:

    标签: arrays flutter dictionary dart iterable


    【解决方案1】:

    这样试试

     final List<String> namesList = myDictionary.map((e) => e["name"].toString()).toList();
    

    【讨论】:

    • 请不要写List作为类型。您正在从toList 中删除结果的泛型类型,这使其成为List&lt;dynamic&gt;。请改用List&lt;String&gt;varfinal
    • 现在它工作了,但现在我需要检查相同的数组并返回该数组中项目的索引
    • 我没听懂你的意思,你能解释一下吗
    • 我做到了?它是 .indexOf() 来获取这个字符串数组中元素的索引
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2011-05-27
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    相关资源
    最近更新 更多