Reputation: 1
Below is the code.
Future<Article> _getArticle(int id) async{
final storyUrl = "https://jsonplaceholder.typicode.com/photos";
final storyRes = await http.get(storyUrl);
if(storyRes.statusCode == 200){
return parseArticle(storyRes.body);
}else{
throw Exception ("Failed to load photos");
}
}
And storyRes is always setting to NULL. I have no idea why?
Upvotes: 0
Views: 784
Reputation: 1646
I have tried to create an Article class from your Json placeholder and it worked like a charm.
Future<Article> _getArticle(int id) async {
final storyUrl = "https://jsonplaceholder.typicode.com/photos";
final storyRes = await http.get(storyUrl);
/** Created an Array from your json via using Article Class*/
final ArtArray = articleFromJson(storyRes.body);
if (storyRes.statusCode == 200) {
print(ArtArray[3999].title);
return parseArticle(storyRes.body[id]);
} else {
throw Exception("Failed to load photos");
}
}
Future<Article> parseArticle(String body) {
}
I haven't Implemented the parseArticle yet, and just added a class for your article and tried to print the result and it worked. Here is the dart class
import 'dart:convert';
List<Article> articleFromJson(String str) => List<Article>.from(json.decode(str).map((x) => Article.fromJson(x)));
String articleToJson(List<Article> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Article {
int albumId;
int id;
String title;
String url;
String thumbnailUrl;
Article({
this.albumId,
this.id,
this.title,
this.url,
this.thumbnailUrl,
});
factory Article.fromJson(Map<String, dynamic> json) => Article(
albumId: json["albumId"],
id: json["id"],
title: json["title"],
url: json["url"],
thumbnailUrl: json["thumbnailUrl"],
);
Map<String, dynamic> toJson() => {
"albumId": albumId,
"id": id,
"title": title,
"url": url,
"thumbnailUrl": thumbnailUrl,
};
}
I hope it will work for you.
Upvotes: 1