更新时间:2022-11-30 11:01:25
jsonDecode(String source)
如果json是这样的,则返回一个列表:
jsonDecode(String source)
return a List if the json is like this:
[{"id": 1,"name":"test theme"}]
,如果json看起来像这样,则返回Map<String,dynamic>
:
and returns a Map<String,dynamic>
if the json looks like this:
{"id": 1,"name":"test theme"}
如果要使用第一个主题,则应执行以下操作:
if you want to use the first theme you should do this:
if (response.statusCode == 200) {
return Theme.fromJson(json.decode(response.body)[0]); // this will return the first theme map
} else {
throw Exception('Failed to load themes');
}
,如果您要将json中的所有主题转换为主题对象,则需要遍历列表并将它们一次一转换:
and if you want to convert all the themes in the json to Theme objects you need to go over the list and convert them one by one:
Future<List<Theme>> getThemes() async {
String url = 'http://10.0.2.2:3000/v1/api/theme';
final response = await get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
List themesList = jsonDecode(response.body);
List<Theme> themes = [];
for(var themeMap in themesList){
themes.add(Theme.fromJson(themeMap));
}
return themes;
} else {
throw Exception('Failed to load themes');
}
}