【问题标题】:flutter Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)扑动未处理的异常:PlatformException(sign_in_failed,com.google.android.gms.common.api.ApiException:10:,null)
【发布时间】:2020-04-29 03:19:18
【问题描述】:

我想用 Google 帐户登录我的应用,但我得到了

ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未处理异常:PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

main.dart:

      import 'package:flutter/cupertino.dart';
      import 'package:flutter/material.dart';
      import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';


      import 'package:firebase_auth/firebase_auth.dart';
      import 'package:google_sign_in/google_sign_in.dart';


      void main() => runApp(MyApp());

      class MyApp extends StatelessWidget {
        // This widget is the root of your application.
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              // This is the theme of your application.
              //
              // Try running your application with "flutter run". You'll see the
              // application has a blue toolbar. Then, without quitting the app, try
              // changing the primarySwatch below to Colors.green and then invoke
              // "hot reload" (press "r" in the console where you ran "flutter run",
              // or simply save your changes to "hot reload" in a Flutter IDE).
              // Notice that the counter didn't reset back to zero; the application
              // is not restarted.
              primarySwatch: Colors.blue,
            ),
            home: MyHomePage(),
          );
        }
      }

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

        // This widget is the home page of your application. It is stateful, meaning
        // that it has a State object (defined below) that contains fields that affect
        // how it looks.

        // This class is the configuration for the state. It holds the values (in this
        // case the title) provided by the parent (in this case the App widget) and
        // used by the build method of the State. Fields in a Widget subclass are
        // always marked "final".


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

      class _MyHomePageState extends State<MyHomePage> {

        bool _value=false;
        final FirebaseAuth _auth = FirebaseAuth.instance;
        final GoogleSignIn googleSignIn = GoogleSignIn();
        Future<String> signInWithGoogle() async {
          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);
          final FirebaseUser user = authResult.user;

          assert(!user.isAnonymous);
          assert(await user.getIdToken() != null);

          final FirebaseUser currentUser = await _auth.currentUser();
          assert(user.uid == currentUser.uid);

          return 'signInWithGoogle succeeded: $user';
        }

        void signOutGoogle() async{
          await googleSignIn.signOut();

          print("User Sign Out");
        }


        @override
        Widget build(BuildContext context) {
          // This method is rerun every time setState is called, for instance as done
          // by the _incrementCounter method above.
          //
          // The Flutter framework has been optimized to make rerunning build methods
          // fast, so that you can just rebuild anything that needs updating rather
          // than having to individually change instances of widgets.
          return Scaffold(

              body:
              Center(
                  child:


                  GoogleSignInButton(
                    onPressed: () {
                      signInWithGoogle().whenComplete(() {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) {
                              return FirstScreen();
                            },
                          ),
                        );
                      });
                    },
                    darkMode: true, // default: false
                  )
              )


            // This trailing comma makes auto-formatting nicer for build methods.
          );
        }
      }

      class FirstScreen extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Container(color: Colors.blue[100]),
          );
        }
      }

项目/build.gradle:

        buildscript {
            ext.kotlin_version = '1.3.50'
            repositories {
                google()
                jcenter()
            }

            dependencies {
                classpath 'com.android.tools.build:gradle:3.5.0'
                classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
                classpath 'com.google.gms:google-services:4.3.2'
            }
        }

        allprojects {
            repositories {
                google()
                jcenter()
            }
        }

        rootProject.buildDir = '../build'
        subprojects {
            project.buildDir = "${rootProject.buildDir}/${project.name}"
        }
        subprojects {
            project.evaluationDependsOn(':app')
        }

        task clean(type: Delete) {
            delete rootProject.buildDir
        }

app/build.gradle

        def localProperties = new Properties()
        def localPropertiesFile = rootProject.file('local.properties')
        if (localPropertiesFile.exists()) {
            localPropertiesFile.withReader('UTF-8') { reader ->
                localProperties.load(reader)
            }
        }

        def flutterRoot = localProperties.getProperty('flutter.sdk')
        if (flutterRoot == null) {
            throw new GradleException("Flutter SDK not found. Define location with 
        flutter.sdk in the local.properties file.")
        }

        def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
        if (flutterVersionCode == null) {
            flutterVersionCode = '1'
        }

        def flutterVersionName = localProperties.getProperty('flutter.versionName')
        if (flutterVersionName == null) {
            flutterVersionName = '1.0'
        }

        apply plugin: 'com.android.application'
        apply plugin: 'kotlin-android'
        apply plugin: 'com.google.gms.google-services'
        apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
         def keystoreProperties = new Properties()
           def keystorePropertiesFile = rootProject.file('key.properties')
           if (keystorePropertiesFile.exists()) {
               keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
           }

        android {
            compileSdkVersion 28

            sourceSets {
                main.java.srcDirs += 'src/main/kotlin'
            }

            lintOptions {
                disable 'InvalidPackage'
            }

            defaultConfig {
                // TODO: Specify your own unique Application ID 
               (https://developer.android.com/studio/build/application-id.html).
                applicationId "batuhan.todo"
                minSdkVersion 16
                targetSdkVersion 28
                versionCode flutterVersionCode.toInteger()
                versionName flutterVersionName
                testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
            }

               signingConfigs {
               release {
                   keyAlias keystoreProperties['keyAlias']
                   keyPassword keystoreProperties['keyPassword']
                   storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
                   storePassword keystoreProperties['storePassword']
               }
           }
           buildTypes {
               release {

                   signingConfig signingConfigs.release

               }
           }
        }

        flutter {
            source '../..'
        }

        dependencies {
            implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
            testImplementation 'junit:junit:4.12'
            androidTestImplementation 'androidx.test:runner:1.1.1'
            androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
            implementation 'com.google.firebase:firebase-analytics:17.2.0'
        }

我有 key.jks 并添加到 Firebase sha-1sha-256 然后更新 google-services.json。我运行 Flutter 干净。我在 Firebase 中启用了 Google 的权限。

我该如何解决这个问题。

我想我尝试了所有解决方案......

【问题讨论】:

  • 它说 登录失败 如果正确,请先检查您的登录实现,让我知道?
  • 如果您处于调试模式,则需要将调试密钥哈希添加到 Firebase 控制台
  • 尝试用flutter clean清理

标签: firebase flutter sha


【解决方案1】:

当应用程序的签名证书的 SHA-1 在 OAuth2 客户端和应用程序的 API 密钥上未正确配置时,会导致从 Google 登录引发的“ApiException 10”。 https://www.google.com/search?q=firebase+auth+apiexception+10

如果您在调试时运行应用,如之前在 cmets 中所述,您需要在 Firebase 项目的应用设置中添加 SHA-1 generated from the debug keystore。如果应用在发布时运行也是如此,应该添加发布密钥库中的 SHA-1。

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 2021-11-28
    • 2019-11-24
    • 2020-01-06
    • 2019-10-04
    • 2021-06-25
    • 2019-11-29
    • 2022-11-02
    • 2021-12-12
    相关资源
    最近更新 更多