How to get the userID in AWS Amplify with Flutter without getting the SignedOutException

  Kiến thức lập trình

I’m using Flutter with AWS Amplify to create users and store their information. After sign-up I want to store user data in DataStore with the document’s ID as the current user’s ID. This is where the problem is actually – getting the user’s ID. The function to retrieve the current user’s ID is a Future and has to be awaited. To do this I’ve tried two approaches which have both failed. Firstly in my saveUserData function, which I shall post later on, I tried adding the line final user = await Amplify.Auth.getCurrentUser(); then on the id in my function, which is the document ID, I did something like this id: user.userId. This failed and I got the SignedOutException: No user is currently signed in error even though this is after I’ve just created a user in the previous sign-up page. This is my saveUserData function:

Future<void> saveUserData() async {
    try {
      final user = await Amplify.Auth.getCurrentUser();

      final model = User(
        id: user.userId,
        email: emailController.text,
        password: passwordController.text,
        username: usernameController.text,

      final result = await;

      return result;
    } on DataStoreException catch (e) {
      throw e.message;
    } catch (e) {

I get the SignedOutException: No user is currently signed in when I do this. And so I tried my second method which was to declare a late variable userId the initialize it. I did this

late String userId;

  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { 
      final user = await Amplify.Auth.getCurrentUser();
      userId = user.userId;

Then I added the userId on my saveUserData function on the id field. This gave me a LateInitializationError: The field 'userId' is not initialized. Please help me find a better way to do this I’d really appreciate it. Thank you