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

Flutter使用amplify_auth_cognito获取AWS Cognito用户详情解决方案

解决方案

Flutter端实现方式

  • 方式1:升级amplify_auth_cognito到1.0及以上稳定版,直接调用官方提供的fetchUserAttributes方法即可获取所有用户属性,你查阅的旧版文档可能未收录该API,示例代码如下:
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_flutter/amplify_flutter.dart';

Future<void> fetchUserInfo() async {
  try {
    final attributes = await Amplify.Auth.fetchUserAttributes();
    String? firstName, lastName, avatarUrl;
    for (final attr in attributes) {
      switch(attr.userAttributeKey) {
        case AuthUserAttributeKey.givenName:
          firstName = attr.value;
          break;
        case AuthUserAttributeKey.familyName:
          lastName = attr.value;
          break;
        case AuthUserAttributeKey.picture:
          avatarUrl = attr.value;
          break;
        default:
          break;
      }
    }
    // 拿到属性后更新UI即可
  } on AuthException catch (e) {
    print('获取用户信息失败: ${e.message}');
  }
}
  • 方式2:如果不方便升级依赖,可以通过调用Cognito公开的userInfo端点获取数据,先拿到当前用户的Access Token,向https://<你的Cognito域名>/oauth2/userInfo发起GET请求,请求头带上Authorization: Bearer <Access Token>即可返回所有标准用户属性。
  • 方式3:如果需要获取自定义用户属性或者结合业务数据,可以在后端部署Lambda接口,调用Cognito Admin API获取全量用户信息,前端通过API Gateway调用该接口即可。

iOS端可用库推荐

  • 官方全量方案:Amplify for iOS的Auth模块,和Flutter端逻辑对齐,同样支持fetchUserAttributes()方法直接拉取Cognito用户属性,适合全栈使用Amplify体系的项目。
  • 轻量原生方案:AWSCognitoIdentityProvider是AWS官方的Cognito原生SDK,不需要集成全量Amplify套件,直接调用getUser方法即可获取所有用户属性,适合仅需要Cognito鉴权功能的项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 02:42:02