Skip to content

Instantly share code, notes, and snippets.

@rurickdev
Last active September 14, 2020 12:23
Show Gist options
  • Save rurickdev/632ec33e15ef1943ac1c04def1cd0352 to your computer and use it in GitHub Desktop.
Save rurickdev/632ec33e15ef1943ac1c04def1cd0352 to your computer and use it in GitHub Desktop.
Null Safety Codes and examples
void main (){
// In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be int.
String name = getFileName(); // getFileName() should return string, never null.
final b = Foo(); // Inferred to be Foo.
// Nullable var declaration just needs an [?] after the type.
int? aNullableInt = null;
var x; // Inferred nullable
// We can define a non-nullable var without his value but it
// need to be initialized before using
int y; // non-nullable int.
print(y); // Analyzer Error.
y = 5;
print(y); // OK
}
void main (){
var myMap = <String, int> {'one': 1};
// Because 'two' doesn't exist, the map will return null
var valueOfTwo = myMap['two']; // Inferred int?
// Because the lookup could return null we can't assign it to a non-nullable
int noNullableInt = myMap['one']; // Analyzer Error
int? nullableInt = myMap['one']; // OK
// we could use [!] if we are shure a key exist
int prettySureNoNull = myMap['one']!; // OK
// But it's allways preferible to use [if] ternary [? :] or null check [??]
int valueOfOne = myMap['one'] ?? 0;
}
void main (){
late int x; // non-nullable int.
print(x); // Analizer Error.
final myMeal = Meal();
print(myMeal.description); // LateInitializationError
myMeal.setDescription('Feijoada!'); // Initialize [description]
print(myMeal.description); // OK
}
class Meal {
late String description; // Class member that will be defined later.
void setDescription(String str) {
description = str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment