0

I have an application with news api from https://newsapi.org/

My model from quicktype:

// To parse this JSON data, do
//
//     final news = newsFromJson(jsonString);

import 'package:meta/meta.dart';
import 'dart:convert';

List<News> newsFromJson(String str) =>
    List<News>.from(json.decode(str).map((x) => News.fromJson(x)));

String newsToJson(List<News> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class News {
  News({
    required this.status,
    required this.totalResults,
    required this.articles,
  });

  final String status;
  final int totalResults;
  final List<Article> articles;

  factory News.fromJson(Map<String, dynamic> json) => News(
        status: json["status"],
        totalResults: json["totalResults"],
        articles: List<Article>.from(
            json["articles"].map((x) => Article.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "totalResults": totalResults,
        "articles": List<dynamic>.from(articles.map((x) => x.toJson())),
      };
}

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

  final Source source;
  final String author;
  final String title;
  final String description;
  final String url;
  final String urlToImage;
  final DateTime publishedAt;
  final String content;

  factory Article.fromJson(Map<String, dynamic> json) => Article(
        source: Source.fromJson(json["source"]),
        author: json["author"] == null ? null : json["author"],
        title: json["title"],
        description: json["description"],
        url: json["url"],
        urlToImage: json["urlToImage"],
        publishedAt: DateTime.parse(json["publishedAt"]),
        content: json["content"],
      );

  Map<String, dynamic> toJson() => {
        "source": source.toJson(),
        "author": author == null ? null : author,
        "title": title,
        "description": description,
        "url": url,
        "urlToImage": urlToImage,
        "publishedAt": publishedAt.toIso8601String(),
        "content": content,
      };
}

class Source {
  Source({
    required this.id,
    required this.name,
  });

  final String id;
  final String name;

  factory Source.fromJson(Map<String, dynamic> json) => Source(
        id: json["id"] == null ? null : json["id"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "name": name,
      };
}

In my remoteservice.dart:

import 'package:http/http.dart' as http;
import 'package:nocovid/models/news.dart';
import 'package:nocovid/utils/constant.dart';

class RemoteServices {
  static var client = http.Client();

  static Future<List<News>?> fetchNews() async {
    final String endpoint =
        'https://newsapi.org/v2/everything?q=covid19&apiKey=' + kAPIKey;
    final Uri url = Uri.parse(endpoint);

    final response = await client.get(url);
    if (response.statusCode == 200) {
      var jsonString = response.body;
      return newsFromJson(jsonString);
    } else {
      return null;
    }
  }
}

newscontroller.dart

import 'package:get/state_manager.dart';
import 'package:nocovid/models/news.dart';
import 'package:nocovid/services/remote_services.dart';

class NewsController extends GetxController {
  var newsList = <News>[].obs;

  @override
  void onInit() {
    fetchNews();
    super.onInit();
  }

  void fetchNews() async {
    var news = await RemoteServices.fetchNews();
    if (news != null) {
      newsList.value = news;
    }
  }
}

And get this errors: enter image description here and enter image description here

the call is performed regularly but upon showing the data, it generates these errors. I checked some codes on github and everything seems to work, while i can't get going

joisberg
  • 175
  • 2
  • 13

1 Answers1

0

Change

List<News> newsFromJson(String str) =>
    List<News>.from(json.decode(str).map((x) => News.fromJson(x)));

To

News newsFromJson(String str) => News.fromJson(json.decode(str));

The Reason for this is News object is not a list, it's a complex JSON with a map that consists of a list of Articles. You need to go through API properly.

If you want a model you can use quicktype. Just paste in the URL response.

Also Change

 static Future<List<News>?> fetchNews() 

to

 static Future<News> fetchNews() 
Krish Bhanushali
  • 1,594
  • 1
  • 8
  • 16