Skip to content

Instantly share code, notes, and snippets.

@DeanPDX
Created January 25, 2023 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeanPDX/87f9464c679febf3019ab3348bab54f2 to your computer and use it in GitHub Desktop.
Save DeanPDX/87f9464c679febf3019ab3348bab54f2 to your computer and use it in GitHub Desktop.
Dart Null Helper Demo
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