skip to Main Content

Here is my code to get the current users phone number.

  Future<void> getCurrentUser() async {
    try {
      AuthUser user = await Amplify.Auth.getCurrentUser();
      print(user.signInDetails);
    } on AuthException catch (e) {
      safePrint('Error retrieving current user: ${e.message}');
    }
  }

The print statement above which extracts the values of the signInDetails array, does not allow me to go deeper one more level. Here is result if I just print the object instance –

CognitoSignInDetailsApiBased {
I/flutter (19338):   "signInType": "apiBased",
I/flutter (19338):   "username": "+14160000000",
I/flutter (19338):   "authFlowType": "USER_SRP_AUTH"
I/flutter (19338): }

How do I just get the value of username element above.

2

Answers


  1. According to the docs you posted, AuthUser#signInDetails returns an instance of SignInDetails, documented here. It looks like there isn’t an accessor username, but there is a toJson() method that returns a map. Given that, you should be able to print just the username value via print(user.signInDetails.toJson()['username'])

    Login or Signup to reply.
  2. You can do this:

    Future<void> getCurrentUser() async {
      try {
        AuthUser user = await Amplify.Auth.getCurrentUser();
    
        if (user.signInDetails is CognitoSignInDetailsApiBased) {
          String username = (user.signInDetails as CognitoSignInDetailsApiBased).username;
    
          print("Username: $username");
        } else {
          print("Unable to retrieve the username.");
        }
      } on AuthException catch (e) {
        safePrint('Error retrieving current user: ${e.message}');
      }
    }
    

    CognitoSignInDetailsApiBased class

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search