Flutter 2: Cast List<dynamic> into List<Map<String, String>>?
502
For the cast, I perform a deep copy of my list using specifiers (as List, as Map<String, String) from the object it returns from the json.decode.
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();
}
Author by
Da2ny
Updated on January 01, 2023Comments
-
Da2ny over 1 year
I am trying to write correctly flutter by precising specific types.
I am collecting data from Json file and try to cast it into a
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); }
However the cast does not works. Even by trying multiple solutions proposed on Stackoverflow, no one is working.
_words
is of typeList<Map<String, String>>
Here the output I get actually
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):
Can someone please provide help for casting my data into my _words's type ?