如何将本地json加载到List <map>变量中?

时间:2018-11-08 10:56:42

标签: json dart flutter

如何将本地json加载到List 变量中?

这是我的本地json。

powershell search: Get-Item : Cannot find path 'C:\Użytkownicy\User\Pulpit\file.txt' because it does not exist.

这是可行的:

[
  {“id”: 00”, “name”: ”TRL”},
  {“id”: 01”, “name”: ”USD”},
  {“id”: 02”, “name”: ”GBP”},
  {“id”: 03”, “name”: ”EUR”},
]

我的问题是我将货币数据移动到currency.json文件中。我可以加载json,但不能分配给List 变量。有什么帮助吗?

更新:

List<Map> _myCurrency = [
  {“id”: 00”, “name”: ”TRL”},
  {“id”: 01”, “name”: ”USD”},
  {“id”: 02”, “name”: ”GBP”},
  {“id”: 03”, “name”: ”EUR”},
];

我收到错误消息;

String jsonTCBanks =
await rootBundle.loadString("packages/capi/currency.json");
List<Map> _myCurrency = json.decode(jsonTCBanks);

如果我使用Map _myCurrency,则json.decode可以运行,但是我松开了键,值属性。

UPDATE-2: 我一直收到以下错误消息:

type 'List<dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>'
  
I/flutter (16273): The following assertion was thrown building MyHomePage(dirty, state: _MyHomePageState#44865):
I/flutter (16273): type 'MappedListIterable<Map<dynamic, dynamic>, DropdownMenuItem<dynamic>>' is not a subtype of type
I/flutter (16273): 'List<DropdownMenuItem<String>>'

1 个答案:

答案 0 :(得分:1)

您需要将其从字符串解码为数据结构,并通过创建所需类型的新列表来调整类型,并在其中传递从jsonDecode返回的列表:

import 'dart:convert';

...

List<Map> _myCurrency = List<Map>.from(jsonDecode(json) as List);
final currencyItems = _myCurrency.map(
    (c) => DropdownMenuItem<String>(c['id'], child: Text(c['name'])).toList();
DropdownButton(items: currencyItems);