You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Google登录点击取消触发PlatformException问题求助

解决Google登录取消时的PlatformException捕获问题

你的代码中,用户取消Google登录流程时抛出的sign_in_canceled异常无法被有效处理,核心原因是当前catch块未针对性区分用户主动取消和真实错误场景。以下是修正后的实现方案:

修正后的代码

Future<UserCredential?> signInWithGoogle() async {
  try {
    final GoogleSignInAccount? utenteGoogle = await GoogleSignIn().signIn();
    
    // 处理部分场景下signIn()返回null的情况(用户取消登录)
    if (utenteGoogle == null) {
      print("用户取消了Google登录");
      return null;
    }

    final GoogleSignInAuthentication datiUtenteGoogle =
        await utenteGoogle.authentication;

    final credenzialiGoogle = GoogleAuthProvider.credential(
      accessToken: datiUtenteGoogle.accessToken,
      idToken: datiUtenteGoogle.idToken,
    );

    return await FirebaseAuth.instance.signInWithCredential(credenzialiGoogle);
  } on PlatformException catch (e) {
    // 精准捕获用户取消登录的异常
    if (e.code == 'sign_in_canceled') {
      print("用户取消了Google登录");
      // 这里可添加自定义逻辑,比如不显示错误提示
    } else {
      print("Google登录出错: ${e.message}");
      // 处理其他真实错误,比如网络问题、配置错误等
    }
    return null;
  } catch (e) {
    // 捕获其他非PlatformException类型的异常
    print("未知登录错误: $e");
    return null;
  }
}

关键修改说明

  • 针对性捕获PlatformException:单独拦截PlatformException并判断code为sign_in_canceled,精准识别用户主动取消行为,避免将其误判为错误。
  • 覆盖signIn()返回null的场景:部分平台或包版本中,用户取消登录会返回null而非抛出异常,增加该判断可覆盖所有取消场景。
  • 分层异常处理:将不同类型的异常拆分处理,方便后续扩展不同场景的用户提示或逻辑。

修改后,用户取消登录的行为会被正确识别,不会再触发无意义的错误日志,同时也能正常处理其他真实登录问题。

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:51:31