Skip to content

Instantly share code, notes, and snippets.

@RedBrogdon
Last active June 9, 2020 16:42
Show Gist options
  • Save RedBrogdon/5a80bfd8e835bb470f56fcc381f901ed to your computer and use it in GitHub Desktop.
Save RedBrogdon/5a80bfd8e835bb470f56fcc381f901ed to your computer and use it in GitHub Desktop.
Snippet 5: Conditional access
// Conditional access is a handy way to
// tighten up code that needs to read
// properties that could be null:
//
// a?.b
//
// The expression above evaluates to the
// value of `b` as long as `a` isn’t
// null. If `a` is null, then the expression
// evaluates to null. Try using conditional
// access to fix this code.
class BigThing {
LittleThing little = LittleThing();
}
class LittleThing {
int fetchInt() => 12;
}
void main() {
final BigThing? big = BigThing();
print('The value is:');
print(big.little.fetchInt());
}
// Without null safety, *two* conditional
// access operators are needed for this
// code to work (one after `big` and one
// after `little`). With null safety,
// conditional access can short-circuit,
// so this expression only requires a
// single `?`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment