final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
Album.fromJson(jsonDecode(dataResponse.body));
在啟用 nullsafety 的專案上,Album.fromJson(jsonDecode(dataResponse.body));此代碼拋出錯誤The argument type 'dynamic' can't be assigned to the parameter type 'Map<String, dynamic>'.
遵循官方檔案
以下代碼用于資料建模。
class Album {
final int userId;
final int id;
final String title;
Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
uj5u.com熱心網友回復:
你只需要投射你的 jsonDecode
Album.fromJson(jsonDecode(dataResponse.body));
顯式型別:
Album.fromJson(jsonDecode(dataResponse.body) as Map<String, dynamic>);
uj5u.com熱心網友回復:
只是您需要將 (Map<String, dynamic> json) 更改為 (dynamic json)
factory Album.fromJson(dynamic json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
uj5u.com熱心網友回復:
模型已經不錯了。。。
試試這個。
final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
List<dynamic> list =jsonDecode(dataResponse.body);
return list.map((e)=>Album.fromJson(e)).toList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/381083.html
