Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart null / false / empty checking: How to write this shorter?

This is my code for true on everything but empty string, null and false:

if (routeinfo["no_route"] == "" || routeinfo["no_route"] == null || routeinfo["no_route"] == false) {     // do sth ... } 

This is my code for true on everything but empty string, null, false or zero:

if (routeinfo["no_route"] == "" || routeinfo["no_route"] == null || routeinfo["no_route"] == false || routeinfo["no_route"] == 0) {     // do sth... } 

How can I write this shorter in Dart? Or is it not possible?

like image 809
Blackbam Avatar asked Feb 24 '17 19:02

Blackbam


People also ask

Does isEmpty check for null Dart?

How to Check String is Empty or Not in Dart (Null Safety)? We can check a string is empty or not by the String Property isEmpty. If the string is empty then it returns True if the string is not empty then it returns False.

How do you check if an object is empty in darts?

Dart Map has built-in properties for checking whether an object is empty or not. length : returns the total number of elements in a Map. If it returns 0 then the map is empty. isEmpty : Checks for an empty map and returns a boolean value, true indicates that the map is empty.

How do you check isEmpty in flutter?

To check if given String is empty in Dart, read isEmpty property of this String. isEmpty is read only property that returns a boolean value of true if the String is empty, or false if the String is not empty.

Is null Falsy in Dart?

This is because Null Safety was finally introduced in Dart/Flutter. But as of October 2020, this feature is still not available for stable releases on dart/flutter.


2 Answers

If your requirement was simply empty or null (like mine when I saw this title in a search result), you can use Dart's safe navigation operator to make it a bit more terse:

if (routeinfo["no_route"]?.isEmpty ?? true) {   //  } 

Where

  • isEmpty checks for an empty String, but if routeinfo is null you can't call isEmpty on null, so we check for null with
  • ?. safe navigation operator which will only call isEmpty when the object is not null and produce null otherwise. So we just need to check for null with
  • ?? null coalescing operator

If your map is a nullable type then you have to safely navigate that:

if (routeinfo?["no_route"]?.isEmpty ?? true) {   // } 
like image 195
Jannie Theunissen Avatar answered Sep 28 '22 04:09

Jannie Theunissen


You could do

if (["", null, false, 0].contains(routeinfo["no_route"])) {   // do sth } 
like image 43
Harry Terkelsen Avatar answered Sep 28 '22 04:09

Harry Terkelsen