【问题标题】:How can I filter List<Map<String, dynamic>> to get a value in Flutter?如何过滤 List<Map<String, dynamic>> 以在 Flutter 中获取值?
【发布时间】:2019-10-01 11:10:39
【问题描述】:

我有一个 json 数据,我正在使用 await jsonDecode. 加载到 List&lt;Map&lt;String, dynamic&gt;&gt;

例如,我有一个;

  1. 金额 = 12500
  2. 口径 = 24

我需要过滤儿子以获得成熟度值:689.19

另外,如果我的金额 = 12500 且价值 = 689.19,我需要获得 24 的口径。

如何过滤 List> json 数据以获取 Flutter 中的值?

[
   {"amount": "5000", "caliber": "12", "maturity":  "484.25"},
   {"amount": "5000", "caliber": "24", "maturity":  "275.67"},
   {"amount": "7500", "caliber": "12", "maturity":  "726.38"},
   {"amount": "7500", "caliber": "24", "maturity":  "413.51"},
   {"amount": "10000", "caliber": "12", "maturity":  "968.50"},
   {"amount": "10000", "caliber": "24", "maturity":  "551.35"},
   {"amount": "12500", "caliber": "12", "maturity":  "1210.63"},
   {"amount": "12500", "caliber": "24", "maturity":  "689.19"},
   {"amount": "15000", "caliber": "12", "maturity":  "1452.76"},
   {"amount": "15000", "caliber": "24", "maturity":  "827.03"},
   {"amount": "15000", "caliber": "12", "maturity":  "1694.89"},
   {"amount": "17500", "caliber": "24", "maturity":  "964.87"},
   {"amount": "17500", "caliber": "36", "maturity":  "727.66"},
   {"amount": "17500", "caliber": "48", "maturity":  "613.53"},
   {"amount": "17500", "caliber": "60", "maturity":  "548.44"},
   {"amount": "20000", "caliber": "12", "maturity":  "1937.01"},
   {"amount": "20000", "caliber": "24", "maturity":  "1102.71"}
]

更新: 在@Muldec 的帮助下,我终于明白了。

首先我将上面的儿子加载到列表中,如下所示。并应用@Muldec 答案,它就奏效了。

List<Map> myList = List<Map>.from(jsonDecode(jsonFastCalculation) as List);
final item = myList.firstWhere((e) => e['amount'] == '12500' && e['caliber'] == '24');
print(item['maturity']);

【问题讨论】:

    标签: list filter flutter where


    【解决方案1】:

    您可以使用列表中的firstWherewhere 方法来获取您需要的Map 元素或Map 的列表,具体取决于您的搜索条件。

    假设您绝对确定您的搜索条件只会给您一个项目(或者您只关心符合条件的第一个项目)这里有一个带有 firstWhere 的代码示例:

    List<Map<String, dynamic>> myList = ....;
    
    final item = myList.firstWhere((e) => e['amount'] == '12500' && e['caliber'] == '24');
    print(item['maturity']);
    

    根据数量和成熟度找到口径,只是在firstWhere方法中更改测试

    【讨论】:

    • 我错了;未处理的异常:NoSuchMethodError:类 '_InternalLinkedHashMap' 没有实例方法 'firstWhere'。
    • 此错误表明您的 json 数据未加载到 List&lt;Map&lt;String, dynamic&gt;&gt; 中,如您之前所述。您能告诉我们您是如何加载数据的吗?
    • 我更新了我的问题,它奏效了。非常感谢
    • 现在如果我用 '$amount' 保留 '12500' 我会遇到空错误:(
    • 当我打印 '$amount' 时,我可以看到其中有价值
    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2023-02-08
    • 2021-09-25
    • 2021-07-26
    • 2021-06-09
    • 2021-09-01
    相关资源
    最近更新 更多