使用 Flutter 登录 Google:错误代码 -4

Son*_*ius 5 ios firebase firebase-authentication flutter

我目前尝试在 Flutter ( https://pub.dartlang.org/packages/google_sign_in ) 中实现 google_sign_in 包。

为此,我遵循了他们存储库的示例(https://github.com/flutter/plugins/blob/master/packages/google_sign_in/lib/google_sign_in.dart)。

在“initState”中的那个例子中是一个调用signInSilently

@override
void initState() {
  super.initState();
  _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
    setState(() {
      _currentUser = account;
      loggedIn = true;
    });
  });
  loggedIn = false;
  _googleSignIn.signInSilently();
}
Run Code Online (Sandbox Code Playgroud)

我在 iOS 中尝试了这段代码。在我的第一个 App Start 中,它运行良好。但是自从我注销后,我每次重新启动我的应用程序时都会收到一个错误。它是以下 PlatformException:

PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.))
Run Code Online (Sandbox Code Playgroud)

我在问题Google Sign-In Error -4 中发现错误代码是因为钥匙串中缺少身份验证。

快速编程时的解决方案是在尝试 signInSilently 之前调用方法 * hasAuthInKeychain*。我的问题是flutter包中的GoogleSignIn类没有这样命名的函数。

是否需要使用此程序包运行另一个调用以确保我可以尝试静默登录?或者我是否做错了什么来获取此消息,或者甚至有可能捕获此错误?

编辑

我也试过马塞尔的解决方案。不知何故,它没有捕获 PlatfromException。

我不知道这是否会有所帮助:signInSilently() 正在调用一个方法,其中有以下调用(google_sign_in.dart,第 217 行):

await channel.invokeMethod(method)
Run Code Online (Sandbox Code Playgroud)

在 platform_channel.dart 中有一个调用

codec.decodeEnvelope(result);
Run Code Online (Sandbox Code Playgroud)

平台异常在这里被抛出。

if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining)
  throw PlatformException(code: errorCode, message: errorMessage, details: errorDetails);
else
  throw const FormatException('Invalid envelope');
Run Code Online (Sandbox Code Playgroud)

编辑 2

由于我只是运行我的应用程序而不是在调试模式下启动它,它以某种方式再次运行而不会引发异常。我不知道这如何影响代码以及为什么会出现此异常。我还可以再次在调试模式下运行代码。

从那以后,我又一次出现了异常。我再次重新启动了 android studio 并在没有调试模式的情况下运行了一次应用程序。

Mar*_*cel 1

PlatformException您可以通过如下处理来检查登录是否失败:

void _setUpGoogleSignIn() async {
  try {
    final account = await _googleSignIn.signInSilently();
    print("Successfully signed in as ${account.displayName}.");
  } on PlatformException catch (e) {
    // User not signed in yet. Do something appropriate.
    print("The user is not signed in yet. Asking to sign in.");
    _googleSignIn.signIn();
  }
}
Run Code Online (Sandbox Code Playgroud)