flutter未处理的异常:PlatformException(sign_in_failed,com.google.android.gms.common.api.ApiException:10:,null)

时间:2020-01-11 22:29:48

标签: firebase flutter sha

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

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

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]),
          );
        }
      }

project / 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 的权限。

如何解决此问题。

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

1 个答案:

答案 0 :(得分:0)

从 Google Sign In 抛出的“ApiException 10”是由于在 OAuth2 客户端和应用程序的 API 密钥上未正确配置应用程序签名证书的 SHA-1 导致的。 https://www.google.com/search?q=firebase+auth+apiexception+10

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