【问题标题】:flutter type cast to List<Map<String, String>>颤振类型转换为 List<Map<String, String>>
【发布时间】:2021-04-16 19:42:52
【问题描述】:

我有一个这样的变量


  List<Map<String, String>> expense = [
    {
      "date": "01-03-2021",
      "person": "John",
    },
    {
      "date": "01-03-2021",
      "person": "John",
    }
    ];

然后

myVar = json.encode(myVar);

现在我如何回到与开始相同的类型变量?我试过这样做,但做不到

json.decode(myVar).toList().map((e) => e as Map<String, String>)?.toList();

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你的类型转换做错了,你不应该在 dynamic 类型上调用 toList(),你的 e as Map&lt;String, String&gt; 也不能工作,因为 edynamic 类型,Dart 将无法推断所有内容的类型,因此将无法正确执行类型转换。以下是您可以投射 JSON 的方法:

    List<Map<String, String>> expense = [
      {
        "date": "01-03-2021",
        "person": "John",
      },
      {
        "date": "01-03-2021",
        "person": "John",
      }
    ];
    
    final myVar = jsonEncode(expense);
    final result = (jsonDecode(myVar) as Iterable)
        .map((e) => Map<String, String>.from(e))
        ?.toList();
    

    输出

    MYVAR: [{"date":"01-03-2021","person":"John"},{"date":"01-03-2021","person":"John"}]
    RESULT: [{date: 01-03-2021, person: John}, {date: 01-03-2021, person: John}]
    

    You can try the full example on DartPad

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2020-01-27
      • 2016-07-21
      • 1970-01-01
      • 2020-04-01
      • 2015-11-21
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多