You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Amplify Auth的CognitoSignInDetailsApiBased对象提取username值?

提取CognitoSignInDetailsApiBased对象中的username字段值

你当前获取用户的代码如下:

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}');
  }
}

打印signInDetails得到的结果为:

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

要提取其中的username值,只需先将signInDetails转换为对应的具体类型CognitoSignInDetailsApiBased,然后直接访问username属性:

Future<void> getCurrentUser() async {
  try {
    AuthUser user = await Amplify.Auth.getCurrentUser();
    if (user.signInDetails is CognitoSignInDetailsApiBased) {
      CognitoSignInDetailsApiBased signInDetails = user.signInDetails as CognitoSignInDetailsApiBased;
      String phoneNumber = signInDetails.username;
      print(phoneNumber); // 输出 +14160000000
    }
  } on AuthException catch (e) {
    safePrint('Error retrieving current user: ${e.message}');
  }
}

添加类型判断能避免类型转换失败的异常,提升代码健壮性。

内容的提问来源于stack exchange,提问作者Sumchans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:04:58