How to handle json api arrays in flutter

92 Views Asked by At

I am getting data from newsapi for my flutter app. How to get the id of the source in this json data?

{
"status": "ok",
"totalResults": 38,


"articles": [

{  

"source": {
"id": "independent",
"name": "Independent"
},
"author": "Rachel Sharp",
"title": "Idaho murders - updates: Moscow police spark confusion over ‘targeted’ attack as crime scene results come back - The Independent",
"description": "Update on Idaho student murders",
"url": example.com,
"urlToImage": example.com,
"publishedAt": "2022-12-01T09:53:10Z",
"content": "ICYMI: Neighbour of victims hits out at Reddit sleuths\r\nA neighbour of the four University of Idaho students who were murdered on 13 November has hit out at Reddit sleuths who claimed that his media"
},
}

ArticleModel.dart

class ArticleModel {
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? content;
  String? publishedAt;

  ArticleModel({required this.author, required this.title, required this.description, required this.url, required this.urlToImage, required this.content, required this.publishedAt});
}

SourceModel.dart

class SourceModel {
  String id;
  String name;
  String description;
  String url;
  String category;
  String country;
  String language;

  SourceModel({required this.id, required this.name, required this.description, required this.url, required this.category,
      required this.country, required this.language});
}

This method returns the list of available sources

class SourceListClass {
  List<SourceModel> source = [];

  Future<void> getSourceList() async {
    String url = "https://newsapi.org/v2/top-headlines/sources?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['sources'].forEach((element) {

        if (element['name'] != null) {

          SourceModel sourceModel = SourceModel(
            id: element['id'],
            name: element['name'],
            description: element['description'],
            url: element['url'],
            category: element['category'],
            country: element['country'],
            language: element['language'],
          );

          source.add(sourceModel);
        }
      });
    }
    print("");
  }
}

With this method I am getting other data except source without issues.

Articles.dart

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async {
    String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['articles'].forEach((element) {

        if (element['urlToImage'] != null && element['description'] != null) {

          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['context'],
            publishedAt: element['publishedAt'],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

I want to add id of the source to this method

1

There are 1 best solutions below

0
Daniel Riffert On

You can access the id of the source with:

var id = element['source']['id'];

Full example:

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async {
    String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['articles'].forEach((element) {

        if (element['urlToImage'] != null && element['description'] != null) {
          
          // get id of source
          var id = element['source']['id'];

          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['context'],
            publishedAt: element['publishedAt'],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

Hope it helps! :)