我是Flutter的新手。从api提取数据,但是会出现这样的错误,
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
如果可以的话请给我一个解决方案,然后我接受您的回答这里有人为此提供解决方案吗?提前致谢。这是我的代码。
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class DisplayScreen extends StatefulWidget {
@override
DisplayScreenState createState() => DisplayScreenState();
}
class DisplayScreenState extends State<DisplayScreen> {
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
Map data;
List userData;
@override
void initState() {
super.initState();
fetchPost();
}
Future fetchPost() async {
http.Response response = await http.get('http://192.168.1.85:4000/getUser');
// print(response.body);
data = await json.decode(response.body);
setState(() {
userData = data["data"];
});
debugPrint(userData.toString());
// return response;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Display'),
),
body: ListView.builder(
itemCount: userData == null ? 0 : userData.length,
itemBuilder: (BuildContext context, int index){
return Card(
child: Row(
children: <Widget>[
Text("${userData[index]["username"]}"),
]
)
);
}
)
);
}
}
response.body看起来像
[{"_id":"5da9593ced22552136120d6c","username":"H","email":"H","password":"H","__v":0},{"_id":"5da95d71ed22552136120d6d","email":"happy@gmail.com","password":"happy","username":"happy","__v":0},{"_id":"5da96010ed22552136120d6e","email":"bchdg","password":"ncbfb","username":"vjfj","__v":0},{"_id":"5da96016ed22552136120d6f","email":"chchdy","password":"bcbchf","username":"fhdgd","__v":0},{"_id":"5da9601bed22552136120d70","email":"chxh","password":"ncnc","username":"chdgd","__v":0},{"_id":"5da96021ed22552136120d71","email":"a","password":"a","username":"a","__v":0},{"_id":"5da98b9aba546b42e2d11182","email":"h","password":"h","username":"h","__v":0}]
答案 0 :(得分:1)
userData = data["data"];
这会尝试将JSON中的“数据”值分配给userData
,但JSON中不存在“数据”。您要获取的列表是JSON本身,因此只需将其分配给userData
即可:
setState({
userData = json.decode(response.body);
});
答案 1 :(得分:0)
您尝试过类似的方法
Any?
您必须将UserData类定义为类似
Iterable l = json.decode(response.body);
List<UserData> posts = l.map((Map model)=> UserData.fromJson(model)).toList();