我是新手,正在运行一段代码以从Internet上获取和显示数据。但是,当我运行代码时,出现此错误:
List<dynamic>' is not a subtype of type 'Map<String, dynamic>
。
我试图找出解决方案,但没有任何帮助。预先感谢。
这是我的代码:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
class Message extends StatefulWidget {
@override
_MessageState createState() => _MessageState();
}
class _MessageState extends State<Message> {
Map data;
List userData;
Future getData() async
{
http.Response response = await http.get('https://jsonplaceholder.typicode.com/users');
data = json.decode(response.body);
setState(() {
userData = data["data"];
});
}
@override
void initState(){
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Container(
child:ListView.builder
(
shrinkWrap: true,
itemCount: userData == null ? 0 : userData.length,
itemBuilder:(BuildContext context, int index){
return Row(
children:<Widget>[
Text('${userData[index]["username"]}', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),),
Text('${userData[index]["catchPhrase"]}',style: TextStyle(fontWeight: FontWeight.w500, fontSize: 17),),
Icon(Icons.navigate_next)
]
);
}
)
);
}
}```
答案 0 :(得分:0)
这是怎么回事,data["data"]
是地图而不是列表。
尝试按照错误日志中的说明将类型更改为Map。
您可以尝试以下吗?
import 'dart:async';
import 'package:http/http.dart' as http;
class Message extends StatefulWidget {
@override
_MessageState createState() => _MessageState();
}
class _MessageState extends State<Message> {
Map data;
Map<String, dynamic> userData;
Future getData() async
{
http.Response response = await http.get('https://jsonplaceholder.typicode.com/users');
data = json.decode(response.body);
setState(() {
userData = data["data"];
});
}
@override
void initState(){
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Container(
child:ListView.builder
(
shrinkWrap: true,
itemCount: userData == null ? 0 : userData.length,
itemBuilder:(BuildContext context, int index){
return Row(
children:<Widget>[
Text('${userData[userData.keys.toList()[index]]["username"]}', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),),
Text('${userData[userData.keys.toList()[index]]["catchPhrase"]}',style: TextStyle(fontWeight: FontWeight.w500, fontSize: 17),),
Icon(Icons.navigate_next)
]);
}
)
);
}
}
答案 1 :(得分:0)
这是您的操作方式:
示例:
型号:
class User {
final int id;
...
User({
@required this.id
...
})
User.fromJson(Map json)
: this.id = json["id"]
...
您将在网络调用中使用此模型,如下所示:
Map<String, dynamic> response = await http.get(...)
List<User> users = (response as List)
.map((element) => User.fromJson(element))
.toList();
P.S。 :我直接在SO中编写了这段代码(未经单元测试。您可能需要做一些细微的调整才能使其正常工作)