2
votes

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(
2

2 Answers

4
votes

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 you'll get an error before compiling.

If you define a variable String? name, and you want to use it later in a Text widget, you'll 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!).

3
votes

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