In FLUTTER / DART, why do we sometimes add a question mark to String when declaring a variable?

In FLUTTER / DART, why do we sometimes add a question mark to String when declaring a variable?

variable_type ? name_of_variable; means that name_of_variable can be null.

variable_type name_of_variable1; means that name_of_variable1 cannot be null and you should initialize it immediately.

late variable_type name_of_variable2; means that name_of_variable2 cannot be null and you can initialize it later.

late variable_type name_of_variable3;
variable_type ? name_of_variable4;
name_of_variable4=some_data;
name_of_variable3=name_of_variable4!;// name_of_variable4! means that you are sure 100% it never will be null

Real example with int type:

int ? a=null; // OK
int  b=null; // b cannot be equal null
late int c =null; // c cannot be equal null
late int d;
d=5; //OK

late int d; // if you never initialize it, you ll got exception

int e=5;
int? f=4;
int ? z;
e=f!; // OK, You are sure that f never are null

e=z!;// You get exception because z is equal null

This is with null safety, the question mark means that this String? can possibly be null and flutter will allow you to assign null to it. String can never be null and youll get an error before compiling.

If you define a variable String? name, and you want to use it later in a Text widget, youll get an error. Because Text widgets only accept non-nullable types. But if you are sure that name will never be null, you tell flutter to not worry about it and that you know what you are doing, you do this by adding the ! like this : Text(name!).

In FLUTTER / DART, why do we sometimes add a question mark to String when declaring a variable?

Leave a Reply

Your email address will not be published. Required fields are marked *