Skip to content

Instantly share code, notes, and snippets.

@kwalrath
Forked from redbrogdon/hint.txt
Last active May 17, 2019 19:58
Show Gist options
  • Save kwalrath/ee3d441f60acc95a07d73762a61b3b98 to your computer and use it in GitHub Desktop.
Save kwalrath/ee3d441f60acc95a07d73762a61b3b98 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; // Unassigned objects are null by default.
// Substitute an operator that makes 'a string' be assigned to baz.
String baz = foo /* TODO */ bar;
void updateSomeVars() {
// Substitute an operator that makes 'a string' be assigned to bar.
bar /* TODO */ 'a string';
}
String foo = 'a string';
String bar; // Unassigned objects are null by default.
// Substitute an operator that makes 'a string' be assigned to baz.
String baz = foo ?? bar;
void updateBar() {
// Substitute an operator that makes 'a string' be assigned 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