[Solved] Fetching data from internet error when object is null

Question

Asked by Filipe G on December 13, 2021 (source).

I have this model that is working as expected except when InfoA returns null:

class ModelGTA {
  ModelGTA({
    required this.infoA,
    required this.infoB,
  });

  InfoA? infoA;
  InfoB? infoB;

  ModelGTA.fromJson(Map<String, dynamic> json) {
    infoA = InfoA.fromJson(json['infoA']);
    infoB = InfoB.fromJson(json['infoB']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['infoA'] = infoA!.toJson();
    _data['infoB'] = infoB!.toJson();
    return _data;
  }
}

class InfoA {
  InfoA({
    required this.data,
    required this.property,
  });

  Data? data;
  Property? property;


  InfoA.fromJson(Map<String, dynamic> json) {
    data = Data.fromJson(json['data']);
    property = Property.fromJson(json['property']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['data'] = data!.toJson();
    _data['property'] = property!.toJson();
    return _data;
  }
}

class Data {
  Dados({
    required this.number,
    required this.type,
  });

  String? number;
  String? type;

  Dados.fromJson(Map<String, dynamic> json) {
    numero = json['number'] ?? "";
    tipo = json['type'] ?? "";
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['number'] = number;
    _data['type'] = type;
    return _data;
  }
}

The problem is that when infoA returns null, the code stops working. and i get this error:

E/flutter ( 9958): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 9958): Receiver: null
E/flutter ( 9958): Tried calling: []("data")

I wonder if there is any way to return an object, Data with empty Strings or prevent the program from trying to access Data when InfoA is null.

Answer

Question answered by Elvis S (source).

change your method ModelGTA.fromJson for this

 ModelGTA.fromJson(Map<String, dynamic> json) {
    infoA =
(json['infoA']==null)?[]: InfoA.fromJson(json['infoA']);
    infoB = InfoB.fromJson(json['infoB']);
  }
DART FLUTTER
SHARE: