-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7-Null.dart
47 lines (40 loc) · 1.46 KB
/
7-Null.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
void main() {
// for nullable types, use ? after the type
int? nullableNum;
print(nullableNum);
// for var and dynamic types, we don't need to use the ? after the type
var varType;
dynamic dynamicType;
print("var: ${varType.runtimeType}");
print("dynamic: ${dynamicType.runtimeType}");
// we can assign null to var and dynamic types
varType = null;
dynamicType = null;
print("after assigning null:");
print("var: ${varType.runtimeType}");
print("dynamic: ${dynamicType.runtimeType}");
// Null aware operator
// (?.), (??), (??=)
print("--------NULL OPERATORS------------");
var obj; // var obj = Num(); if we don't want to assign null to obj
int? number;
if (obj != null) {
number = obj.num;
}
// if we omit the if statement, we get an error
print(number);
// the solution is to use the null aware operator (?.)
number = obj?.num; // this means : if obj is not null, then get the num property of obj otherwise return null
print(number);
// if we want to assign a default value if the value is null, we can use the null aware operator (??)
number = obj?.num ?? 0; // this means : if obj is not null, then get the num property of obj otherwise return 0 instead of null
print(number);
// if we want to assign a default value if the value is null, we can use the null aware operator (??=)
var checkNum;
checkNum ??= 100; // this means : if checkNum is null, then assign 100 to checkNum otherwise do nothing
print(checkNum);
// can be useful when dealing with APIs
}
class Num {
int num = 10;
}