Home > Mobile >  E/flutter ( 2874): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null
E/flutter ( 2874): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null

Time:04-14

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);
    }

CodePudding user response:

Looks like you're trying to parse the articles with the wrong perception about your JSON data template.

First, deserialize your JSON data from the network response.

json.decode(response.body);

Preview

Network response is provided as an object with 3 initial keys:

  • status
  • totalResults
  • articles

All your articles are stored in the key named "articles" and it is a list. So first try to parse the value of articles key to a list of Map<String, dynamic>

List<Map<String, dynamic>>.from(json.decode(response.body)["articles"]);

Now, on the final step, map your List<Map<String, dy

return List<Map<String, dynamic>>.from(json.decode(response.body)["articles"]).map((json) => Article.fromJson(json)).toList();

There you go. Happy coding :D

  • Related