E/flutter ( 2874): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'Map

I am pretty new to flutter and programming as a whole, I would appreciate if anyone could help with this error.

can anyone put me through how I can put a null check before converting response to json? I have tried doing this but to no avail.

Apparently this error is pointing to my model.

import 'dart:convert';

Article articleFromJson(String str) => Article.fromJson(json.decode(str));

String articleToJson(Article data) => json.encode(data.toJson());


class Article {
  Article({
    required this.source,
    required this.author,
    required this.title,
    required this.publishedAt,
  });

  Source source;
  String author;
  String title;
  DateTime publishedAt;

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

  Map<String, dynamic> toJson() => {
        "source": source.toJson(),
        "author": author,
        "title": title,
        "publishedAt": publishedAt.toIso8601String(),
      };
}

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

  dynamic id;
  String name;

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

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

This is the class I created to fetch the data.

import 'package:breaking_news_app/models/article.dart';
import 'package:http/http.dart' as http;

class NetworkHelper {
  Future<List<Article>?> getArticles() async {
    var client = http.Client();

    var url = Uri.parse(
        'https://newsapi.org/v2/top-headlines?country=us&apiKey=0bf7d5ec422248a980f7dfc082ee2e7d');
    var response = await client.get(url);
    if (response.statusCode == 200) {
      var json = response.body;
      return [articleFromJson(json)];
    } else {
      //  ignore: avoid_print
      print(response.statusCode);
    }


Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)