Flutter variable initialization fails

86 views Asked by At

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

There are 2 answers

0
gretal On

You can use a nullable type and check if the variable is null before using it.

String? uid;

@override
void initState() {
  fetchUserID();
  super.initState();
}

void fetchUserID() async {
  final user = await Amplify.Auth.getCurrentUser();
  setState(() {
    uid = user.userId;
  });
}

AlSO // Check if uid is null before using it.

1
Mirza Maulana On

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.

late String? uid;

  @override
  void initState() {
    fetchUserID().then((value) { uid = value; setState(() {}); });
    super.initState();
  }

 Future<String> fetchUserID() async {
    final user = await Amplify.Auth.getCurrentUser();
    return user.userId;
  }

Then you can do the check in build method by using if statement

if (uid == null) return SizedBox();
return SomeWidgetHere();