我正在尝试通过精确的特定类型来正确编写 flutter。
我正在从 Json 文件收集数据并尝试将其转换为
List<Map<String, String>>
。
Future<void> _readJson() async {
final String response = await rootBundle.loadString('lib/assets/vocabulary.json');
final data = await json.decode(response);
print(data);
_words = List<Map<String, String>>.from(data);
}
但是演员阵容不起作用。即使尝试了 Stackoverflow 上提出的多种解决方案,也没有一个能奏效。
_words
属于类型 List<Map<String, String>>
这是我实际得到的输出
I/flutter ( 3971): 0
I/flutter ( 3971): [{a: test1, b: test2}, {a: test3, b: test4}, {a: test5, b: test6}]
E/flutter ( 3971): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'
E/flutter ( 3971): #0 new List.from (dart:core-patch/array_patch.dart:40:5)
E/flutter ( 3971): #1 _HomePageState._readJson (package:langage_trainer/pages/home/home_page.dart:108:14)
E/flutter ( 3971): <asynchronous suspension>
E/flutter ( 3971):
有人可以提供帮助将我的数据转换为我的 _words 类型吗?
对于转换,我使用说明符执行列表的深层复制(如列表、地图
Future<void> _readJson() async {
final String response = await rootBundle.loadString('lib/assets/vocabulary.json');
final List<Map<String, String>> data = (await json.decode(response) as List)
.map((e) => e as Map<String, String>).toList();
}
为了防止在处理 JSON 数据时出现任何子类型错误,最好单独转换每个
Map
元素。
// Assuming you got this data
List<Map<String, dynamic>> jsonlist = [
{'foo': 'bar', 'hello': 'world'},
{'aaa': 'bbb', 'ccc': 'ddd'},
];
print(jsonlist.runtimeType); // List<Map<String, dynamic>>
// Cast individually
var data = jsonlist.map((item) => item.cast<String, String>()).toList();
print(data.runtimeType); // List<Map<String, String>>