0

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.

Sumchans
  • 3,088
  • 6
  • 32
  • 59
  • What does `AuthUser` look like? More specifically, what is the type of `signInDetails`? Does that type have a field, getter, or method that can return `username` from it? – anqit Jul 13 '23 at 04:00
  • @anqit This is what gets printed onto the console if I do print(AuthUser) ```CognitoAuthUser { I/flutter (19338): "userId": "66e708f8-dc6c-4dcf-8521-1a37d7c12305", I/flutter (19338): "username": "66e708f8-dc6c-4dcf-8521-1a37d7c12305", I/flutter (19338): "signInDetails": { I/flutter (19338): "signInType": "apiBased", I/flutter (19338): "username": "+14160000000", I/flutter (19338): "authFlowType": "USER_SRP_AUTH" I/flutter (19338): }``` – Sumchans Jul 13 '23 at 16:51
  • @anqit this is what the AuthUser class is https://pub.dev/documentation/amplify_core/latest/amplify_core/AuthUser-class.html – Sumchans Jul 13 '23 at 18:59
  • So looking at the doc for `SignInDetails` (https://pub.dev/documentation/amplify_core/latest/amplify_core/SignInDetails-class.html), it looks like there is a `toJson()` method that returns a map. Given that, does `print(user.signInDetails.toJson()['username'])` do what you are looking for? – anqit Jul 13 '23 at 22:20
  • @anqit Thanks. Can you put it as an answer? – Sumchans Jul 13 '23 at 23:26

2 Answers2

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'])

anqit
  • 780
  • 3
  • 12
1

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

Hamed
  • 5,867
  • 4
  • 32
  • 56