颤振类型转换为 List<Map<String, String>>

时间:2021-04-16 19:42:52

标签: flutter dart

我有一个这样的变量


  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();

1 个答案:

答案 0 :(得分:0)

你的类型转换做错了,你不应该在 toList() 类型上调用 dynamic,你的 e as Map<String, String> 也不会工作,因为 e 是 {{1 }} type 和 Dart 将无法推断所有内容的类型,因此将无法正确执行类型转换。以下是您如何投射 JSON:

dynamic

输出

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();

You can try the full example on DartPad