Taki
Taki

Reputation: 3730

Nullable values using flutter 2.+

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

enter image description here

Upvotes: 0

Views: 495

Answers (1)

webaddicted
webaddicted

Reputation: 1079

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

}

       

Upvotes: 2

Related Questions