flutter - 如何捕获 GoogleSignInsignInSilently 中的错误?

标签 flutter dart

我有以下代码,用于静默登录用户

try {
    result = await GoogleSignIn().signInSilently().catchError((x) {
      print(x);
    });
  } catch (e) {
    print(e);
  }

如果用户无法静默登录,则会导致错误。

PlatformException (PlatformException(sign_in_required, com.google.android.gms.common.api.ApiException: 4: 4: , null))

我遇到的问题是我似乎无法捕获异常。 catchError 和 catch block 都没有被命中。我如何捕捉这个错误?

最佳答案

在您的方法中执行以下操作

try {
    result = await GoogleSignIn().signInSilently(suppressErrors: false).catchError((x) {
      print(x);
    });
  } catch (e) {
    print(e);
  }

默认情况下suppressErrors = true抑制您想要捕获的错误消息。

查看source code

SignInSilently 方法用于抑制错误消息,从而不会抛出您想要捕获的异常。

从此方法的文档中:

  /// When [suppressErrors] is set to `false` and an error occurred during sign in
  /// returned Future completes with [PlatformException] whose `code` can be
  /// either [kSignInRequiredError] (when there is no authenticated user) or
  /// [kSignInFailedError] (when an unknown error occurred).

完整方法

 /// Attempts to sign in a previously authenticated user without interaction.
  ///
  /// Returned Future resolves to an instance of [GoogleSignInAccount] for a
  /// successful sign in or `null` if there is no previously authenticated user.
  /// Use [signIn] method to trigger interactive sign in process.
  ///
  /// Authentication process is triggered only if there is no currently signed in
  /// user (that is when `currentUser == null`), otherwise this method returns
  /// a Future which resolves to the same user instance.
  ///
  /// Re-authentication can be triggered only after [signOut] or [disconnect].
  ///
  /// When [suppressErrors] is set to `false` and an error occurred during sign in
  /// returned Future completes with [PlatformException] whose `code` can be
  /// either [kSignInRequiredError] (when there is no authenticated user) or
  /// [kSignInFailedError] (when an unknown error occurred).
  Future<GoogleSignInAccount> signInSilently({bool suppressErrors = true}) {
    final Future<GoogleSignInAccount> result = _addMethodCall('signInSilently');
    if (suppressErrors) {
      return result.catchError((dynamic _) => null);
    }
    return result;
  }

引用

关于flutter - 如何捕获 GoogleSignInsignInSilently 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776203/

相关文章:

flutter - var 和 final 变量中的 UI 实现部分之间的区别

dart - 如何从 flutter 应用程序中导航到网页? (OAuth)

dart - 有没有办法调用 4 个 API,然后创建一个列表并绘制一个饼图

css - 如何在 Dart/Polymer 中隐藏卡片上的元素标签?

flutter - 如何在 Dart 中获得小数部分

android - Flutter:后退时关闭应用程序不起作用

http - 如果http请求失败,如何添加超时?

dart - 滚动 Controller flutter 错误发生异常

ios - 尝试为 iOS 构建 flutter 应用程序时出现问题

flutter - 如何在 flutter 中动态隐藏和显示底栏