Created
July 4, 2019 14:10
-
-
Save nikli2009/2c425f60bf7415695b2af25423993e6f to your computer and use it in GitHub Desktop.
Dart Safe Operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
// ? Operator | |
Coke myCoke = Coke(volume: 600); | |
// this is unsafe as anyone can change volume before printing. | |
// for example, myCoke = null | |
// then it gonna throw an error. | |
print(myCoke.volume); // 600 | |
// so let's use ? as null check operator to ensure this won't happen | |
// means if it is null, if null, stop and return null | |
// otherwise continue ".volumne" | |
myCoke = null; | |
print(myCoke?.volume); // null | |
// ?? Operator | |
// To set default value | |
print(myCoke?.volume ?? '550'); // 550 | |
myCoke = Coke(volume: 500); | |
myCoke.volume = 700; | |
print(myCoke?.volume ?? '550'); // 700; | |
} | |
class Coke { | |
// 300 ml | |
int volume = 330; | |
Coke({ this.volume }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment