Flutter Android Studio 错误 - ApiException:10

问题描述 投票:0回答:0

我已经有两天遇到同样的错误了,问题是 Android Studio 给我的唯一错误是; “谷歌:PlatformException(sign_in_failed,com.google.android.gms.common.api.ApiException:10:,null,null)”

我正在尝试使用 Firebase 登录

查了很多资料也没找到解决办法。之前它确实给了我更多的错误,但我一直在打磨它,直到只剩下这个。

我给你留下一些配置,你可以看看是否正确。

Image1

Image2

Image3

我有 firebase_options.dart,还安装了 firebase-tools-instant-win.exe,进行登录。

我的 android/build.gradle 是:

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

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

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

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

tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

我的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: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    namespace "com.example.untitled"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

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

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.untitled"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion 20
        targetSdkVersion 34
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true

        signingConfigs {
            release {
                storeFile file("xxxxxxxxx.jks")
                storePassword 'xxxxxxx'
                keyAlias 'xxxxxxxkey'
                keyPassword 'xxxxxxx'
            }
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'com.google.firebase:firebase-analytics'
    implementation platform('com.google.firebase:firebase-bom:32.2.0')
}

我的Main调用Firebase,在Main代码中我怀疑有任何错误,它一定是外部的。由于没有出现错误并且没有 firebase YES,所以有登录

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

我认为问题出在凭据中,因为我无法创建“创建 OAuth 客户端 ID”,因为它告诉我“请求失败,因为 Android 包名称和指纹已在使用中”

Image4

SHA 密钥是正确的...其他一切都正确,检查了一、二、三...四次,我没有在任何地方看到任何错误。

预先感谢,抱歉我的英语!

PS:我添加了 Main 的代码,删除了所有内容(因为它是一个非常完整的代码),只留下启动会话的“逻辑”。

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:logger/logger.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Inicio de Sesión con Firebase')),
        body: const SignInWithGoogleButton(),
      ),
    );
  }
}

class SignInWithGoogleButton extends StatefulWidget {
  const SignInWithGoogleButton({Key? key}) : super(key: key);

  @override
  State<SignInWithGoogleButton> createState() => _SignInWithGoogleButtonState();
}

class _SignInWithGoogleButtonState extends State<SignInWithGoogleButton> {
  final Logger _logger = Logger();
  bool _isSignedIn = false;

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

  Future<void> _checkSignInStatus() async {
    final preferences = await SharedPreferences.getInstance();
    setState(() {
      _isSignedIn = preferences.getBool('isSignedIn') ?? false;
    });
  }

  Future<void> _signInWithGoogle() async {
    try {
      final GoogleSignIn googleSignIn = GoogleSignIn();
      final GoogleSignInAccount? googleUser = await googleSignIn.signIn();

      if (googleUser != null) {
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
        final AuthCredential credential = GoogleAuthProvider.credential(
          accessToken: googleAuth.accessToken,
          idToken: googleAuth.idToken,
        );
        final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
        final User? user = userCredential.user;

        if (user != null) {
          setState(() {
            _isSignedIn = true;
          });

          final preferences = await SharedPreferences.getInstance();
          preferences.setBool('isSignedIn', true);
        }
      }
    } catch (error) {
      _logger.e('Error al iniciar sesión con Google: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: _isSignedIn ? null : _signInWithGoogle,
        child: Text(_isSignedIn ? 'Ya iniciaste sesión' : 'Iniciar sesión con Google'),
      ),
    );
  }
}
flutter firebase android-studio dart google-signin
© www.soinside.com 2019 - 2024. All rights reserved.