android - _TypeError(类型'列表' 不是类型 'Map 的子类型') 颤动
问题描述
我有一个问题,因为 2 小时。我有这个错误,我看到了更多的主题,但我无法解决它。
消息:_TypeError(类型'List'不是类型'Map'的子类型)颤动
我的模型:
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();
},
),
),
);
}
}
我尝试了更多的教程和不同的主题,但我有同样的错误......
谢谢 !
解决方案
jsonDecode(String source)
如果 json 是这样的,则返回一个 List:
[{"id": 1,"name":"test theme"}]
Map<String,dynamic>
如果 json 看起来像这样,则返回 a :
{"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 中的所有主题转换为 Theme 对象,则需要遍历列表并一一转换:
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');
}
}
推荐阅读
- linux - systemd-networkd-wait-online.service 在启动时失败
- php - 我们如何用逗号将不同的输入字段存储在表的同一列上,
- php - Laravel 事件阻止更新模型
- wordpress - 无法创建新的 Wordpress 数据库表
- javascript - LookAt 矩阵(归一化平行投影)
- javascript - 为什么从模拟类中的另一个函数调用函数的测试失败?
- javascript - 下拉菜单导航栏问题
- php - 在 sprintf 中添加 html
- npm-install - 无法在 Windows 中安装 npm。已安装node@12
- r - @-登录输出/列表