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?
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.
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.
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.
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.
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) { // }
You could do
if (["", null, false, 0].contains(routeinfo["no_route"])) { // do sth }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With