0

I have created a model class to use with dio library and fetch data , and in flutter 2.+ , they have introduced null safy , when i created the model class i got error to make values nullable , it worked with primitive types by adding ? but for the model itself , i don't know how to do it , if anyone could help , would be so appreciated , thank you

  • This is screenshot from my android studio

enter image description here

Taki
  • 3,290
  • 1
  • 16
  • 41

1 Answers1

2

From flutter 2+ they provided nullable because of null value it show error. you need to define const default value or append the ? operator to specify that the variable is of a Nullable type.

class SearchPhotoRespo {
  int? _total;
  int? _totalPages;
  List<Results>? _results;

  int? get total => _total;
  int? get totalPages => _totalPages;
  List<Results>? get results => _results;

  SearchPhotoRespo({
      int? total, 
      int? totalPages, 
      List<Results>? results}){
    _total = total;
    _totalPages = totalPages;
    _results = results;
}

  SearchPhotoRespo.fromJson(Map<String, dynamic> json) {
    _total = json["total"];
    _totalPages = json["total_pages"];
    if (json["results"] != null) {
      _results = [];
      json["results"].forEach((v) {
        _results?.add(Results.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["total"] = _total;
    map["total_pages"] = _totalPages;
        if (_results != null) {
      map["results"] = _results?.map((v) => v.toJson()).toList();
    }
    return map;
  }

}

       
Nisanth Reddy
  • 5,967
  • 1
  • 11
  • 29
webaddicted
  • 1,071
  • 10
  • 23
  • As you see from my comment you also define nullable member variable of call like : int? _total; int? _totalPages; List? _results; – webaddicted Jun 08 '21 at 03:19
  • i have also used late keyword and it worked as well thank you , but i have a function that return a future as well , it is asking me to make it nullable , here is a screenshot https://ibb.co/BZWjLNH – Taki Jun 08 '21 at 03:25