两个小时以来我有问题。 我遇到此错误,我看到了更多主题,但无法解决。
消息:_TypeError(类型“列表”不是类型“地图”的子类型)扑通
我的模特:
class Theme {
int id;
String name;
Theme({this.id, this.name});
factory Theme.fromJson(Map<String, dynamic> json) {
return Theme(
id: json['id'],
name: json['name'],
);
}
Future<Theme> getThemes() async {
String url = 'http://10.0.2.2:3000/v1/api/theme';
final response =
await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
return Theme.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load themes');
}
}
}
我的主题屏幕:
class _Theme extends State<Theme> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Blackbox"),
),
body: Center(
child: FutureBuilder<t.Theme>(
future: t.Theme().getThemes(), //sets the getQuote method as the expected Future
builder: (context, snapshot) {
if (snapshot.hasData) {
new ListView.builder(
itemCount: _lengthList,
itemBuilder: (BuildContext context, int index) {
return Container(
child: new Text('${snapshot.data.name}'),
);
},
);//checks if the response returns valid data
} else if (snapshot.hasError) { //checks if the response throws an error
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
),
);
}
}
我尝试了更多的教程和不同的主题,但我有相同的错误...
谢谢!
答案 0 :(得分:1)
jsonDecode(String source)
如果json是这样,则返回一个列表:
[{"id": 1,"name":"test theme"}]
,如果json看起来像这样,则返回Map<String,dynamic>
:
{"id": 1,"name":"test theme"}
如果要使用第一个主题,则应执行以下操作:
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中的所有主题转换为主题对象,则需要遍历列表并将它们一一转换:
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');
}
}