skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search