flutter Необработанное исключение: PlatformException (sign_in_failed, com.google. android .gms.common.api.ApiException: 10:, null) - PullRequest
0 голосов
/ 12 января 2020

Я хочу войти в систему с помощью Google для моего приложения, но я получаю

ОШИБКА: трепетание / 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-1 и sha-256, затем обновите google-services. json. Я пробежал Флаттер чисто. Я включил разрешение с Google в Firebase .

Как я могу исправить эту проблему.

Полагаю, я попробовал каждое решение ...

...