I am new in Flutter. fetch data from api but it gives an error like this,
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
Please give me a solution if it works then I accept your answer Anyone here with a solution for this? Thanks in Advance. Here is my code.
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 is looking like,
[{"_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}]
userData = data["data"];
This tries to assign the value of "data" from your JSON to userData
, but "data" does not exist within your JSON. The list you want to obtain is the JSON itself, so simply assign that to userData
instead:
setState({
userData = json.decode(response.body);
});
Have you tried something like this
Iterable l = json.decode(response.body);
List<UserData> posts = l.map((Map model)=> UserData.fromJson(model)).toList();
you'll have to define the UserData class to be something like this
class UserData {
/// Json is a Map<dynamic,dynamic> if i recall correctly.
static fromJson(json): Post {
UserData data = new UserData()
data._id = ...
data.userName = ...
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.