flutter - AWS Amplify for Flutter:用户已登录但无法获取当前用户
问题描述
在将 AWS Amplify 引入我的颤振项目时,我遇到了一个奇怪的问题。
我有以下代码。当我尝试登录用户时。我进入InvalidStateException(message: There is already a user which is signed in. Please log out the user before calling showSignIn., recoverySuggestion: Operation performed is not a valid operation for the current auth state, underlyingException: null)
(AuthException
在signIn
函数的末尾,图像中的第 70 行)。
但是,当我尝试获取当前用户时,异常显示我已经退出。
感觉是矛盾的。有人可以帮忙吗?谢谢
signIn(String password, void Function(String, String) onSuccess,
Future<void> Function(String) onFailure) async {
AuthUser? currentUser;
try {
currentUser = await Amplify.Auth.getCurrentUser();
if (currentUser.username == _username) {
_isSignIn = true;
} else {
await Amplify.Auth.signOut();
_isSignIn = false;
}
} on Exception catch (e) {
_isSignIn = false;
}
try {
SignInResult res;
if (!_isSignIn) {
res = await Amplify.Auth.signIn(
username: _username,
password: password,
);
if (res.isSignedIn) {
_isSignIn = res.isSignedIn;
currentUser = await Amplify.Auth.getCurrentUser();
}
}
if (_isSignIn && currentUser != null) {
List<AuthUserAttribute> attributes =
await Amplify.Auth.fetchUserAttributes();
onSuccess(
currentUser.userId,
attributes
.firstWhere(
(attribute) => attribute.userAttributeKey == 'email')
.value);
_isEmailVerified = attributes
.firstWhere((attribute) =>
attribute.userAttributeKey == 'email_verified')
.value ==
'true';
}
} on NotAuthorizedException catch (notAuthorizedException) {
await onFailure(notAuthorizedException.message);
} on AuthException catch (e) {
print(e);
final a = await Amplify.Auth.getCurrentUser();
await onFailure(e.message);
}
}
解决方案
尝试在每个 signIn() 之前调用 signOut(),这样可以确保避免冲突:
void signIn() async {
try {
await Amplify.Auth.signOut();
} on AuthException catch (e) {
}
SignInResult res = await Amplify.Auth.signIn(
username: userNameController.text.trim(),
password: passwordController.text.trim());
if (res.isSignedIn) {
_isSignIn = res.isSignedIn;
currentUser = await Amplify.Auth.getCurrentUser();
}
}
推荐阅读
- jquery - 尝试使用未加载的地图:world_mill
- java - 动态窗格的 JavaFX 约束问题
- sql - 如果另一个请求中存在元素,如何让列等于 true?
- azure - 如何从 Azure 函数返回流?
- ruby-on-rails - 如何将活动记录数据库添加回使用 --skip-active-record 创建的 Rails 5
- node.js - GraphQL/Prisma 客户端服务器错误:变量“$data”不能是非输入类型“LinkCreateInput!”。(第 1 行,第 18 列)
- ruby-on-rails - Rails - 如何删除除一条符合条件的记录之外的所有记录
- java - 如何检测空的多部分数据传输
- python - 需要对字符串 join() 方法进行一点说明
- android-studio - Android Studio 的 Memory Profiler 中的“总计数”指标是什么?