Unhandled Exception: PlatformException (sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) - works well in one system
Asked Answered
H

4

5

I am developing a Bluetooth application using platform channel in flutter (using Java). But while I try to login with google-sign in( google_sign_in: ^4.5.6 ) I'm getting the error. I can login the details but I can't move to further page...... Actually, it's working in my office system, but when I copy the project and run in another it gives the error...Can anyone please help

main.dart
import 'package:bmsapp2/pages/loginpage.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(BmsApp());
}

class BmsApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    const curveHeight = 12.0;
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.amber[900],
            shape: const MyShapeBorder(curveHeight),
          ),
          body: LoginPage(),
        ),
      ),
    );
  }
}

class MyShapeBorder extends ContinuousRectangleBorder {
  const MyShapeBorder(this.curveHeight);
  final double curveHeight;

  @override
  Path getOuterPath(Rect rect, {TextDirection textDirection}) => Path()
    ..lineTo(0, rect.size.height)
    ..quadraticBezierTo(
      rect.size.width / 2,
      rect.size.height + curveHeight * 2,
      rect.size.width,
      rect.size.height,
    )
    ..lineTo(rect.size.width, 0)
    ..close();
}

loginpage.dart
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:avatar_glow/avatar_glow.dart';

import 'bluetoothpage.dart';

final GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['profile', 'email']);

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isAuth = false;
  GoogleSignInAccount _currentUser;

  Widget buildAuthScreen() {
    //return Text(_currentUser.displayName ?? '');
    return SafeArea(
      child: Center(
        child: Container(
          margin: EdgeInsets.only(top: 50),
          child: Column(
            //mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircleAvatar(
                backgroundColor: Colors.white,
                backgroundImage: NetworkImage(_currentUser.photoUrl),
                radius: 50,
              ),
              SizedBox(height: 15),
              Text(
                'You are logged in as ',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 15,
                ),
              ),
              SizedBox(height: 5),
              Text(
                _currentUser.email,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                ),
              ),
              ElevatedButton(
                onPressed: _logout,
                child: Text("Logout".toUpperCase(),
                    style: TextStyle(fontSize: 14, letterSpacing: 2)),
                style: ButtonStyle(
                    foregroundColor:
                        MaterialStateProperty.all<Color>(Colors.white),
                    backgroundColor:
                        MaterialStateProperty.all<Color>(Colors.amber[900]),
                    shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5),
                            side: BorderSide(color: Colors.amber[900])))),
              ),
              Container(
                // height: 300,
                child: AvatarGlow(
                  glowColor: Colors.blue,
                  endRadius: 70.0,
                  duration: Duration(milliseconds: 2000),
                  repeat: true,
                  showTwoGlows: true,
                  repeatPauseDuration: Duration(milliseconds: 100),
                  child: Material(
                    elevation: 4.0,
                    shape: CircleBorder(),
                    child: CircleAvatar(
                      backgroundColor: Colors.grey[200],
                      child: Image.asset(
                        'images/bt.png',
                        height: 40,
                        width: 250,
                        fit: BoxFit.fitWidth,
                      ),
                      radius: 40.0,
                    ),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => BluetoothPage()));
                },
                child: Text('Find your device',
                    style: TextStyle(fontSize: 15, letterSpacing: 2)),
                style: ButtonStyle(
                    foregroundColor:
                        MaterialStateProperty.all<Color>(Colors.white),
                    backgroundColor:
                        MaterialStateProperty.all<Color>(Colors.amber[900]),
                    shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5),
                            side: BorderSide(color: Colors.amber[900])))),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _login() {
    googleSignIn.signIn();
  }

  _logout() {
    googleSignIn.signOut();
  }

  Widget buildUnAuthScreen() {
    return Scaffold(
        body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            child: Image.asset('images/touch.png'),
          ),
          SizedBox(
            height: 5.0,
          ),
          Text(
            'Next Generation Battery',
            style: TextStyle(fontSize: 15, color: Colors.grey),
          ),
          SizedBox(
            height: 5.0,
          ),
          Container(
            child: GestureDetector(
              onTap: () {
                _login();
              },
              child: Image.asset(
                'images/signin.png',
                height: 75,
                width: 250,
                fit: BoxFit.fitWidth,
              ),
            ),
          ),
          Text(
            'Sign up here',
            style: TextStyle(fontSize: 15, color: Colors.grey),
          ),
        ],
      ),
    ));
  }

  void handleSignin(GoogleSignInAccount account) {
    if (account != null) {
      print('User Signed in $account');

      setState(() {
        isAuth = true;
        _currentUser = account;
      });
    } else {
      setState(() {
        isAuth = false;
        //_currentUser = null;
      });
    }
  }

  @override
  void initState() {
    super.initState();

    googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
      handleSignin(account);
    }, onError: (err) {
      print('Error Signiing in : $err');
    });
    // Reauthenticate user when app is opened
    /*googleSignIn.signInSilently(suppressErrors: false).then((account) {
      handleSignin(account);
    }).catchError((err) {
      print('Error Signiing in : $err');
    });*/
  }

  @override
  Widget build(BuildContext context) {
    return isAuth ? buildAuthScreen() : buildUnAuthScreen();
  }
}

error:
E/flutter (12476): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)
E/flutter (12476): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:581
E/flutter (12476): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:158
E/flutter (12476): <asynchronous suspension>
E/flutter (12476): #2      MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
E/flutter (12476): <asynchronous suspension>
E/flutter (12476):
D/ViewRootImpl@4370975[SignInHubActivity](12476): mHardwareRenderer.destroy()#1
D/ViewRootImpl@4370975[SignInHubActivity](12476): Relayout returned: oldFrame=[0,0][1440,2560] newFrame=[0,0][1440,2560] result=0x5 surface={isValid=false 0} surfaceGenerationChanged=true
D/ViewRootImpl@4370975[SignInHubActivity](12476): mHardwareRenderer.destroy()#4
D/ViewRootImpl@4370975[SignInHubActivity](12476): dispatchDetachedFromWindow
D/InputTransport(12476): Input channel destroyed: fd=102

Hsinking answered 29/3, 2021 at 16:23 Comment(1)
#77340376 may help you.Needless
L
9

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) apiException:10 means it's most likely due to incorrect setup of SHA-1 or SHA-256. Since you said that it works at the office, it's probably a different environment than what you are working with now, and you should add these keys. This is also assuming that you are running a debug build, so add your debugging SHA-1 keys.

Lingual answered 29/3, 2021 at 17:2 Comment(5)
Thank you .It helps .But If i'm going to change the SHA key for the project settings in firebase , its not going to work in other environment(in office) right.Hsinking
No it continues to work, you can add as much sha keys as you need. This is basically telling firebase which environments are allowed. Every key added, allows an environment to access the project. Does this solve your problem?Lingual
oh..Thank you.I will try and let you know .Thank you once again.Hsinking
You're most welcome, if this helps you, kindly consider accepting this and marking it as an answer. Happy coding.Lingual
I followed the above code with getting it's SHA1 from: Google Play Console -> Your App -> Setup -> App signing but still having the upper mentioned error. Remember I am not using Firebase, using direct Google Signin...Fulgurite
B
6

Also this problem happens with the apps downloaded from Google Play. This is because Google signs your app with it's own key which is not accessible for you. You can get it's SHA1 from: Google Play Console -> Your App -> Setup -> App signing

Bratislava answered 16/7, 2021 at 3:19 Comment(1)
This was exactly my problem. I needed the sha1 from the google to add in the firebase project settings. Either the documentation was lacking or I was just blind :) thank you so much for this - it ended an odyssey of about 2h :)Statutable
K
6

Recently fixed this issue after many tries, After updating to flutter-3.1.0-pre9, and Updating Android studio to chipmunk 2021.2.1, I got an interesting debug message. The google sign in works well on iOS, but no matter what I did, I keep getting this exact message PlatformException (sign_in_failed... blah blah blah

The new error message now has this also: clientId is not supported on Android and is interpreted as serverClientId. Use serverClientId

Adding clientId as the parameter on Android seems to be the problem

Make sure your keystore sha-1 is registered on firebase and you have completed the instructions as stated on firebase

late GoogleSignIn googleSignIn;
***
@override
void initState() {
 ***
 googleSignIn = GoogleSignIn(
        scopes: [
          'email',
          'https://www.googleapis.com/auth/userinfo.profile',
        ],
        serverClientId: isIOS ? null : googleClientId,
        clientId: isIOS ? googleClientIdIOS : null);
 ***

This way you set clientId while on iOS and serverClientId on Android. Hope this help.

Kinslow answered 1/8, 2022 at 13:10 Comment(1)
This was the issue with my side after 2 hours of debugging was not aware the clientId broke the android side of things. Thank you!Ohg
B
0

kindly look at this thread as this explains the process of rectifying the error:

https://mcmap.net/q/1920895/-unhandled-exception-platformexception-sign_in_failed-com-google-android-gms-common-api-apiexception-10-null-null

Balliett answered 10/7, 2024 at 9:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.