I am trying to implement the below code block but User _user
showing warning as:
Non-nullable instance field ‘_user’ must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it, or mark it ‘late’.dartnot_initialized_non_nullable_instance_field
class _LandingPageState extends State<LandingPage> {
User _user;
@override
Widget build(BuildContext context) {
if (_user == null) {
return const SigninScreen();
}
return Container();
}
}
How to initialize this value?
I tried this but it’s not working.
User _user = null;
3
Answers
In flutter/dart we don’t initialize variables as null using
User _user = null;
like in other languages.You can either do one of the following based on your need :
?
sign like thisUser? _user;
, now the handling of null workslate
like thislate User _user;
which will tell Dart compiler that it will be initialized before use, else you will get error during runtimeAs per your logic of checking
if (_user == null)
, There are chances that the value of variable_user
will become null. But you have defined the variable as non nullable .Now, what you can do is just make the data type
nullable
by adding a?
By adding a
?
at the end of a datatype, you are making the variable nullable.Please check the updated code
additionally, You cant define the value of a variable like
User user = null;
while initializing, you can define like
User? user;
and the value ofuser
will benull
by default (you dont have to explicitly give null value while initializing).and whenever you want to modify the value of
user
and to make it null, you can try value assigning likeuser = null;
What?
You are close. The issue here is that you haven’t declared the
_user
variable to be nullable. This is done by putting a?
right after the Type.This is called "Sound Null Safety", you can read more about it here.
How to apply this to your case
When declaring
_user
you need to add a?
afterUser
, like so:Full example