簡體   English   中英

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

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

我正在使用 flutter 中的平台通道(使用 Java)開發藍牙應用程序。 但是,當我嘗試使用 google-sign in( google_sign_in: ^4.5.6 ) 登錄時,我遇到了錯誤。 我可以登錄詳細信息,但無法移至更多頁面......實際上,它在我的辦公系統中工作,但是當我復制項目並在另一個項目中運行時,它給出了錯誤......任何人都可以幫忙

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

[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可能是由於 SHA-1 或 SHA-256 設置不正確。 既然您說它在辦公室工作,它可能與您現在使用的環境不同,您應該添加這些密鑰。 這也假設您正在運行調試版本,因此添加您的調試 SHA-1 密鑰。

從 Google Play 下載的應用程序也會出現此問題。 這是因為 Google 使用自己無法訪問的密鑰為您的應用程序簽名。 您可以從以下位置獲取它的 SHA1:Google Play Console -> Your App -> App Integrity。

最近經過多次嘗試修復了這個問題,在更新到flutter-3.1.0-pre9,並將Android studio更新到chipmunk 2021.2.1后,我收到了一條有趣的調試消息。 google sign in iOS 上運行良好,但無論我做什么,我都會收到這個確切的消息PlatformException (sign_in_failed... blah blah blah

新的錯誤消息現在也有: clientId is not supported on Android and is interpreted as serverClientId. Use serverClientId clientId is not supported on Android and is interpreted as serverClientId. Use serverClientId

在 Android 上添加clientId作為參數似乎是問題所在

確保您的密鑰庫sha-1已在 firebase 上注冊,並且您已完成 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);
 ***

這樣,您可以在 iOS 上設置clientId ,在serverClientId上設置 serverClientId。 希望這有幫助。

暫無
暫無

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

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