Getting this when trying to initialize data.
The following LateError was thrown building UserProfile(dirty, state: _UserProfileState#752a9): LateInitializationError: Field '_userData@32329253' has not been initialized."
Here's the code:
late final User _user;
late final DocumentSnapshot _userData;
@override
void initState() {
super.initState();
_initUser();
}
void _initUser() async {
_user = FirebaseAuth.instance.currentUser!;
try {
_userData = await FirebaseFirestore.instance
.collection('users')
.doc(_user.uid)
.get();
} catch (e) {
print("something went wrong");
}
}
The build function is not even running as i tried to print _user and _userData to check if they have been initialized.
If i try to print _user and _userData in initUser() function, _user gets printed and _userData gets printed after the error statements.
Please help me find a way out through this error.
How to Solve Error? Remember: You have to assign something to the late variable before using it. Here, we have created a nullable variable, which is assigned to the Text() widget, When you use Text(name!) null check operator instead shown like above, you may get "Null check operator used on a null value" Error.
Error thrown when a late variable is accessed in an invalid manner. A late variable must be initialized before it's read. If a late variable has no initializer expression and has not been written to, then reading it will throw a late initialization error.
By the time the constructor body (the code in braces) starts, the object must be fully initialized so all its fields are usable, including d in the example. So if d is not initialized in 1 , 2 or 3 , it fails to compile. We can fix this by declaring d to be late : It literally means “I will initialize it later”.
In my case, I faced this error while using easy_localization
. I forgot:
await EasyLocalization.ensureInitialized();
on main.dart file.
P.S. I know this is not the answer to this question, I wrote this for someone who faced this issue like my case.
Even though you are initializing these variables inside the initUser()
, but you will get this error if you are using the variables inside the build()
method since initUser()
is asynchronous meaning it will take time to get the data from the collection. To solve this you can do:
@override
void initState() {
super.initState();
_initUser().whenComplete((){
setState(() {});
});
}
This will rebuild the widget tree with the new values.
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