0

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?

1
  • Can you share the contents of the Article class and the parseArticle function? Commented Oct 13, 2019 at 13:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.