Created
January 25, 2023 18:42
-
-
Save DeanPDX/87f9464c679febf3019ab3348bab54f2 to your computer and use it in GitHub Desktop.
Dart Null Helper Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
// Can return null item | |
var item = getItem(true); | |
print(emptyIfNull(item?.name)); // Prints "empty" | |
var notNull = getItem(false); | |
print(emptyIfNull(notNull?.name)); // Prints "Hello!" | |
} | |
// Demo class | |
class MyItem { | |
String? name; | |
} | |
// Helper to get either an item or null. | |
MyItem? getItem(bool returnNull) { | |
if (returnNull) { | |
return null; | |
} | |
var item = MyItem(); | |
item.name = "Hello!"; | |
return item; | |
} | |
// Helper function to change null into string. | |
String emptyIfNull(String? item) { | |
if (item != null) { | |
return item; | |
} | |
return "empty"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment