DEV Community

Cover image for The main 3 point of Null safety in Flutter
Hosain Mohamed
Hosain Mohamed

Posted on

The main 3 point of Null safety in Flutter

This is would be a quick summary of null safety, explained in 3 points.

1- Question mark (?)

2- Exclamation mark (!)

3- late keyword

1 - Question mark (?) = Nullable
This can be used to tell compiler that this variable can be null.

String? name ;

If (?) is removed there would be a compiler error. as this variable could be null.

2 - exclamation mark (!) = Non Nullable
When converting from String ? (nullable string) to String
there would be no error as (nullable string) can contain a
value or can be null.

String name = "ahmed"; (Non nullable)
String? newName = name; πŸ‘ŒπŸ‘Œ

The problem when converting from String to String ? (nullable
string) as String cannot contain a null value.

String? name ; (Nullable)
String newName = name; πŸ€¦β€β™‚οΈπŸ€¦β€β™‚οΈ (Compiler error )

And this can be solved in 3 ways :
1 -

String? name ;
if( name!=null ){
String newName = name;
}

2-
String? name ;
String newName = name ?? "ahmed";

3-
String? name ;
String newName = name !;

last solution is using (!) when we tell the compiler that
name cannot be null and you should be sure of that and this
is preferred to be used under restricted condition otherwise
there would be a runtime error if name is null.

3- late keyword
This is simply can be used when you assign a value to a variable but later on like when you do in initState() function.

late String name ;
void initState() {
name = "ahmed"

super.initState();
}

Hope this was a helpful review on Null safety principles in Flutter.
Thank you for reading.

Top comments (0)