In the demo app, we find an instance of "final String? title;" - > Why do we add this "?" after the type String ?
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
**final String? title;**
@override
_MyHomePageState createState() => _MyHomePageState();
}
In the same way, why when using it, we add a "!" ?
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: **Text(widget.title!),**
),
body: Center(
Nullable and non-nullable typesIf you want a variable of type String to accept any string or the value null , give the variable a nullable type by adding a question mark ( ? ) after the type name. For example, a variable of type String? can contain a string, or it can be null.
How to Declare Variable in Dart. We need to declare a variable before using it in a program. In Dart, The var keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned to the variable because Dart is an infer type language.
double question mark operator means "if null".
Strings are mainly used to represent text. A character may be represented by multiple code points, each code point consisting of one or two code units. For example, the Papua New Guinea flag character requires four code units to represent two code points, but should be treated like a single character: "🇵🇬".
"!" is a new dart operator for conversion from a nullable to a non-nullable type. Read here and here about sound null safety. Use it only if you are absolutely sure that the value will never be null and do not confuse it with the conditional property access operator.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With