在AWS Amplify Cognito中获取用户ID时==运算符报错排查
Flutter Amplify Cognito 获取用户ID(sub)失败的修复方案
错误原因
你遇到的问题核心是类型不匹配:element.userAttributeKey并非普通字符串,而是Amplify Auth库定义的AuthUserAttributeKey类型(枚举或封装类),直接和字符串"sub"用==比较永远无法匹配,导致firstWhere找不到目标属性,最终抛出异常(你代码中未处理找不到的场景,会进入catch块,所以userId无法正确赋值)。
修复方法
方法一:使用预定义常量匹配(推荐)
Amplify已经为常用属性提供了预定义的AuthUserAttributeKey常量,直接用AuthUserAttributeKey.sub匹配即可:
Future<String> _getUserIdFromAttributes() async { try { final attributes = await Amplify.Auth.fetchUserAttributes(); final userId = attributes .firstWhere((element) => element.userAttributeKey == AuthUserAttributeKey.sub) .value; debugPrint('User ID: $userId'); return userId; } catch (e) { debugPrint('获取用户ID失败: ${e.toString()}'); rethrow; } }
方法二:转换为字符串后匹配
如果需要通过字符串值匹配,可调用AuthUserAttributeKey的key属性(对应实际的字符串键值)进行比较:
Future<String> _getUserIdFromAttributes() async { try { final attributes = await Amplify.Auth.fetchUserAttributes(); final userId = attributes .firstWhere((element) => element.userAttributeKey.key == "sub") .value; debugPrint('User ID: $userId'); return userId; } catch (e) { debugPrint('获取用户ID失败: ${e.toString()}'); rethrow; } }
额外优化建议
使用firstWhere时建议添加orElse回调,明确处理找不到属性的场景,避免抛出未捕获的异常:
final userId = attributes .firstWhere( (element) => element.userAttributeKey == AuthUserAttributeKey.sub, orElse: () => throw Exception('用户属性中未找到sub(用户ID)'), ) .value;
内容的提问来源于stack exchange,提问作者Christian.E
相关产品推荐
相关产品推荐

