I am new to Flutter/Dart but I have experience with Typescript. Can you help me with the following code and question:
final String? title;
appBar: title != null
? AppBar(
title: Text(title),
)
: null,
I am getting the error message The argument type 'String?' can't be assigned to the parameter type 'String'
.
I thought that the condition title != null
would ensure that title
is not null. Is there a better way to handle this? to not add just Text(title!),
?
3
Answers
Dart is null-safe,
so you can’t define a variable without giving it an init value,
you may define an init value and it will be an empty string or if you are sure that you will give value to that variable before assigning it to the screen you can use late keyword, Note that if you misuse it and didn’t assign a value before the screen is built, you will get a null error in the screen.
if you want it to accept that title could be a string or null you put the ? after String.
if you want to use that variable you need to put The null assertion operator (!)
telling dart that you are sure it won’t be null during runtime
refer to this documentation to have a better understanding of Null Safety in Dart Null Safety
Only local variables can be used like that because there are situations where the
title
can returnnull
the second time it’s accessed. So you could do this if you really don’t want to use!
To give an example of why it’s not guaranteed that
title
is not null the second time consider this program:Note I had to put the
!
in the print line otherwise it wouldn’t compile. But also note that this possibly can throw an exception since it’s possibletitle
returns null after the null check.use null aware operator to assign a default value when title is null, as Text widget expects a non null value.