I declared a late variable – late String uid;
as shown and tried to initialize it later on. This is my full code
late String uid;
@override
void initState() {
fetchUserID();
super.initState();
}
void fetchUserID() async {
final user = await Amplify.Auth.getCurrentUser();
uid = user.userId;
}
but I get LateInitializationError: The field uid has not been initialized
. I’m not really certain what’s wrong there and not sure what to do to fix that. I’d really appreciate any help. Thank you
2
Answers
You can use a nullable type and check if the variable is null before using it.
AlSO // Check if uid is null before using it.
In dart, you can’t use late for Future method just like that. Because the Future method can return error if something bad happened, meanwhile late variable requires exact value as its type at that time of moment.
Then you can do the check in build method by using if statement