如何将本地 json 加载到 List
这是我本地的 json.
[
{“id”: 00”, “name”: ”TRL”},
{“id”: 01”, “name”: ”USD”},
{“id”: 02”, “name”: ”GBP”},
{“id”: 03”, “name”: ”EUR”},
]
然而这有效:
List<Map> _myCurrency = [
{“id”: 00”, “name”: ”TRL”},
{“id”: 01”, “name”: ”USD”},
{“id”: 02”, “name”: ”GBP”},
{“id”: 03”, “name”: ”EUR”},
];
我的问题是我将货币数据移至currency.json 文件中。我可以加载 json,但无法分配给 List 变量。有什么帮助吗?
UPDATE:
String jsonTCBanks =
await rootBundle.loadString("packages/capi/currency.json");
List<Map> _myCurrency = json.decode(jsonTCBanks);
我得到的错误是;
type 'List<dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>'
如果我使用 Map _myCurrency json.decode 可以工作,但我会丢失键、值属性。
更新2:我不断收到错误:
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>>'
class _MyHomePageState extends State<MyHomePage> {
String _mySelectedCurrency;
List<Map> _myCurrencies;
@override
void initState() {
// TODO: implement initState
super.initState();
_loadLocalJsonData();
}
Future _loadLocalJsonData() async {
String jsonCurrency = await rootBundle
.loadString("packages/capi/currency.json");
setState(() {
_myCurrencies = List<Map>.from(jsonDecode(jsonCurrency) as List);
print("*******_myCurrencies: $_myCurrencies");// This part works correctly
});
}
@override
Widget build(BuildContext context) {
return _myCurrencies == null ? _buildWait(context) : _buildRun(context);
}
// TODO: BUILD RUN
Widget _buildRun(BuildContext context) {
final _itemsName = _myCurrencies.map((c) {
return new DropdownMenuItem<String>(
value: c["id"].toString(),
child: new Text(c["name"].toString()),
);
}).toList();
return new Scaffold(
key: _scaffoldKey,
body: new SafeArea(
top: false,
bottom: false,
child: new Form(
key: _formKey,
child: new ListView(
padding: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 32.0),
children: <Widget>[
//TODO: CURRENCY ###########################################
new FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
labelText: 'CHOOSE CURRENCY',
labelStyle: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
color: Colors.green.shade700),
errorText: state.hasError ? state.errorText : null,
),
isEmpty: _mySelectedCurrency == '',
child: new DropdownButtonHideUnderline(
child: new DropdownButton<String>(
style: TextStyle(
fontSize: 14.0,
color: Colors.black,
fontWeight: FontWeight.w500,
),
value: _mySelectedCurrency,
isDense: true,
onChanged: (String newValue) {
setState(() {
_mySelectedCurrency = newValue;
state.didChange(newValue);
});
},
items: _itemsName,
),
),
);
},
validator: (val) {
return val != '' ? null : 'Choose Currency...';
},
),
],
))));
}
// TODO: BUILD WAIT
Widget _buildWait(BuildContext context) {
return new Scaffold(
body: new Center(child: CircularProgressIndicator()),
);
}
}