簡體   English   中英

使用 Flutter 登錄 Google:錯誤代碼 -4

[英]Google Sign-In With Flutter: Error Code -4

我目前嘗試在 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();
}

我在 iOS 中嘗試了這段代碼。 在我的第一個 App Start 中,它運行良好。 但是自從我注銷后,我每次重新啟動我的應用程序時都會收到一個錯誤。它是以下 PlatformException:

PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.))

我在問題Google Sign-In Error -4 中發現錯誤代碼是因為鑰匙串中缺少身份驗證。

快速編程時的解決方案是在嘗試 signInSilently 之前調用方法 * hasAuthInKeychain*。 我的問題是flutter包中的GoogleSignIn類沒有這樣命名的函數。

是否需要使用此程序包運行另一個調用以確保我可以嘗試靜默登錄? 或者我是否做錯了什么來獲取此消息,或者甚至有可能捕獲此錯誤?

編輯

我也試過馬塞爾的解決方案。 不知何故,它沒有捕獲 PlatfromException。

我不知道這是否會有所幫助:signInSilently() 正在調用一個方法,其中有以下調用(google_sign_in.dart,第 217 行):

await channel.invokeMethod(method)

在 platform_channel.dart 中有一個調用

codec.decodeEnvelope(result);

平台異常在這里被拋出。

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');

編輯 2

由於我只是運行我的應用程序而不是在調試模式下啟動它,它以某種方式再次運行而不會引發異常。 我不知道這如何影響代碼以及為什么會出現此異常。 我還可以再次在調試模式下運行代碼。

從那以后,我又一次出現了異常。 我再次重新啟動了 android studio 並在沒有調試模式的情況下運行了一次應用程序。

您可以通過像這樣處理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();
  }
}

這是捕獲錯誤並運行 _googleSignIn.signIn(); 的一種方法;

GoogleSignInAccount googleSignInAccount = await googleSignIn
    .signInSilently(suppressErrors: false)
    .catchError((dynamic error) async {
  GoogleSignInAccount googleSignInAccount =
      await _googleSignIn.signIn();
});

就我而言,我不希望用戶自動看到登錄窗口。 在這種情況下,我從改變signInsignOut 這樣,我將用戶發送到另一個帶有解釋性消息和登錄按鈕的視圖。

GoogleSignInAccount googleSignInAccount = await googleSignIn
    .signInSilently(suppressErrors: false)
    .catchError((dynamic error) async {
      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signOut();
      return googleSignInAccount;
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM