Component - Null safety
This Flutter component demonstrates null safety by safely handling a nullable string. It shows how to check if a value is null before using it, preventing app crashes.
This Flutter component demonstrates null safety by safely handling a nullable string. It shows how to check if a value is null before using it, preventing app crashes.
Scaffold
├─ AppBar
│ └─ Text
└─ Center
└─ Column
├─ Text (displays message)
└─ ElevatedButton (toggles message)? symbol mean when used after a type in Flutter null safety?? usage in Flutter? after a type means the variable can be null, allowing it to hold either a value or null.?, variables must always have a non-null value, so ? explicitly allows null.? means nullable = A [OK]? means nullable, can hold null [OK]? makes variable constant? with non-nullable? means read-only? immediately after the type name, like int?.int? number; which is correct. int number?; places ? after variable name, which is invalid. nullable int number; uses a non-existent keyword. int number = null; assigns null to a non-nullable type, causing error.int? [OK]? right after type to make nullable [OK]? after variable name?int? a; int b = a ?? 5; print(b);
a is nullable and not initialized, so it is null.??a ?? 5 means if a is null, use 5 instead.a is null, b gets 5, so print(b) outputs 5.?? gives default if null = 5 [OK]?? to provide default when null [OK]?? returns nullString? name; print(name.length);
name is nullable and not initialized, so it is null.name.length without null check causes error because name might be null.name?.length or check for null before accessing.?. or check null before property access [OK]List<int>? numbers;, which code safely sums all elements or returns 0 if the list is null?numbers can be null, accessing methods directly risks error.?. to safely call reduce only if numbers is not null, then ?? 0 to default to 0 if null. int sum = numbers.reduce((a, b) => a + b); calls reduce directly, causing error if null. int sum = numbers!.reduce((a, b) => a + b); forces non-null with !, risky if null. int sum = numbers == null ? null : numbers.reduce((a, b) => a + b); returns null instead of int 0, causing type mismatch.?. with ?? for safe nullable operations [OK]! without null checkPass the test and this pattern moves unknown