如何将本地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>>'
答案 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);