Skip to content

Instantly share code, notes, and snippets.

@ThinkDigitalSoftware
Last active September 27, 2018 18:25
Show Gist options
  • Save ThinkDigitalSoftware/2de781ac5cca62020f93271cb2df2169 to your computer and use it in GitHub Desktop.
Save ThinkDigitalSoftware/2de781ac5cca62020f93271cb2df2169 to your computer and use it in GitHub Desktop.
Null-aware Operators in Dart Examples
main() {
// ?? operator
print("\n?? operator \n");
var x; // x is null
String otherExp = "x is null";
print(x ?? otherExp); // returns otherExp, which is a String, to print.
var isXNull = x ?? true;
print(isXNull);
//is the same as
if (x == null)
print(otherExp);
else
print(x);
if (x == null) isXNull = true;
print(isXNull);
// ??= operator
// assigns a value if the left side is null.
print("\n??= operator \n");
var imNull;
var imNotNull = 5;
imNull ??= 5;
imNotNull ??= 6; // this expression will not assign 6 because
// [imNotNull] is not null.
print(imNull);
print(imNotNull);
// this is the same as
if (imNull == null) imNull = 5;
if (imNotNull == null) imNotNull = 6;
print(imNull);
print(imNotNull);
// ?. operator
// used to call a method if the object is not null, otherwise, returns null;
print("\n?. operator \n");
String nullString;
String notNullString = "Hello, world!";
print(nullString?.contains("Hello"));
print(notNullString.contains("Hello"));
if (nullString == null)
print(null);
else
print(nullString.contains("Hello"));
if (notNullString == null)
print(null);
else
print(notNullString.contains("Hello"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment