Reputation: 592
I am learning flutter and trying to parse a json which is array or json objects like this.
[
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"albumId": 1,
"id": 2,
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
},]
And here is my fetch function which fetches this data from server.
fetch() async{
var client = new http.Client();
try {
var uriResponse = await
client.get('https://jsonplaceholder.typicode.com/photos');
if(uriResponse.statusCode == 200){
var data = json.decode(uriResponse.body);//data is array of objects
List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();
setState(() {
photos = data;
_isLoading = false;
});
}
} finally {
client.close();
}
}
But the line ;
List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();
gives me error that:
ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '(Map<String, dynamic>, dynamic) => Photo' is not a subtype of type '(dynamic) => dynamic' of 'f'
Here is my Photo PODO class.
class Photo {
final int id;
final String title;
final String url;
final String thumbnailUrl;
Photo({this.id, this.title,this.url, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as int,
title: json['title'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
url: json['url'] as String,
);
}
}
What i am doing wrong in the above code? Thanx in advance !
Upvotes: 2
Views: 2443
Reputation: 66
In my project I have done like this and its working
pics = (data as List).map((model) => Photo.fromJson(model)).toList();
Upvotes: 1
Reputation: 4319
You can use quicktype it lets you copy in your JSON string and generates the Dart Objects
Upvotes: 2
Reputation: 426
try this if it didnt work make sure to print the the response body
Iterable<dynamic> l = json.decode(uriResponse.body);
List<Post> posts = l.map((model) => Post.fromJson(model)).toList();
Upvotes: 0
Reputation: 3987
Try using
pics = data.map((i)=>Photo.fromJson(i)).toList();
You are receiving an json array and not json object from server
Upvotes: 0