首页 > 解决方案 > 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)AuthExceptionsignIn函数的末尾,图像中的第 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);
    }
  }

标签: flutteraws-amplify

解决方案


尝试在每个 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();
    }
 
}

推荐阅读