Should a field be left null or initialized to a default value when fetching data from an API in null safe Dart?

Issue

Should I set a value to every null fields when retrieving something something from an api? Or should I keep them null and check when displaying them if they aren’t null?

Ex:

  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
    type: json["type"] == null ? 'Point' : json["type"],
    coordinates: json["coordinates"] == null ? [] : List<double>.from(json["coordinates"].map((x) => double.tryParse(x))),
  );

or

  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
    type: json["type"] == null ? null : json["type"],
    coordinates: json["coordinates"] == null ? null : List<double>.from(json["coordinates"].map((x) => double.tryParse(x))),
  );

Edit –> or should I be doing this in an other way like this maybe?

  factory Location.fromJson(Map<String, dynamic> json) {
    return Location(
      geo: json["geo"] = Geo.fromJson(json["geo"]),
      city: json["city"] = json["city"],
      country: json["country"] = json["country"],
      area: json["area"] = json["area"],
    );
  } 

Solution

null-safety in Dart is not a campaign to get rid of null. null is a valid information.

Take the easiest example: does my wife want a pizza? Seems like an easy true/false question. Until you consider that "I haven’t asked her yet" is indeed a real world state that is just as valid.

So no, you should not replace all your null values with something else. You would lose information.

So again: null safety does not mean you get rid of the null value. It means you no longer get surprised by the null value.

If you have values that can legitimately be null, then let them be.

You got improved compiler support now to make sure you don’t drop the ball and mistakenly assume they are always non-null. That’s great. Be happy about it.

Answered By – nvoigt

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *