Skip to content

Instantly share code, notes, and snippets.

@redbrogdon
Last active May 17, 2019 19:55
Show Gist options
  • Save redbrogdon/f8ab52228b9c03aee9504dbdc15d797d to your computer and use it in GitHub Desktop.
Save redbrogdon/f8ab52228b9c03aee9504dbdc15d797d to your computer and use it in GitHub Desktop.
DartPad Cheatsheet Codelab - 2 - Null-aware operators
All you need to do in this exercise is replace the TODO comments with either ?? or ??=.
Read the codelab text to make sure you understand both, and then give it a try.
String foo = 'a string';
String bar = null;
// Which operator assigns 'a string' to baz?
String baz = foo /* TODO */ bar;
void updateSomeVars() {
// Which operator assigns 'a string' to bar?
bar /* TODO */ 'a string';
}
String foo = 'a string';
String bar = null;
// Which operator assigns 'a string' to baz?
String baz = foo ?? bar;
void updateBar() {
// Which operator assigns 'a string' to bar?
bar ??= 'a string';
}
void main() {
final errs = <String>[];
try {
updateSomeVars();
if (foo != 'a string') {
errs.add('Looks like foo somehow ended up with the wrong value.');
} else if (bar != 'a string') {
errs.add('Looks like bar ended up with the wrong value.');
} else if (baz != 'a string') {
errs.add('Looks like baz ended up with the wrong value.');
}
} catch (e) {
errs.add('Tried calling updateSomeVars and received an exception: ${e.runtimeType}.');
}
if (errs.isEmpty) {
_result(true);
} else {
_result(false, errs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment