Canceling Google Sign In causes Flutter exception

I am trying to implement Google Sign In in my Android Flutter app, but when the user cancels Google sign in (by tapping the back button) an exception is thrown:

PlatformException (PlatformException(sign\_in\_canceled, com.google.android.gms.common.api.ApiException: 12501: , null))

I am using google_sign_in version 4.1.1 which should return null instead of an exception. I have tried wrapping my code in a try-catch block and using .catchError() on the method, but neither approach has solved the problem. My code looks like this:

  Future googleSign(BuildContext context) async {
    final GoogleSignInAccount googleSignInAccount =
        await googleSignIn.signIn().catchError((onError) => print(onError));

    final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

    final AuthResult authResult = await _auth.signInWithCredential(credential);

    return authResult.user.uid;
  }

Do you have any suggestions on how to handle this exception?

You can try modifying your code to catch the PlatformException specifically, like this:

  Future googleSign(BuildContext context) async {
    try {
      final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
      final GoogleSignInAuthentication googleSignInAuthentication =
          await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );

      final AuthResult authResult = await _auth.signInWithCredential(credential);

      return authResult.user.uid;
    } on PlatformException catch (error) {
      print(error);
      return null;
    }
  }

This should catch the specific PlatformException that is being thrown when the sign in is cancelled and return null instead of throwing an exception.