我正在用颤振编写 Firebase 应用程序,但我收到有关 google-services.json 和初始化的错误

Posted

技术标签:

【中文标题】我正在用颤振编写 Firebase 应用程序,但我收到有关 google-services.json 和初始化的错误【英文标题】:I am coding a Firebase app with flutter but i am getting errors about google-services.json and inititilization 【发布时间】:2021-06-17 17:19:21 【问题描述】:

我正在编写一个注册屏幕,我正在使用 Firebase,但我遇到了这个错误。但在我的项目中,我在 android\app 中有 google-services.json。我不明白你为什么能帮助我? 我从 firebase 的站点进行了初始化和操作

E/flutter (26694):[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] 未处理的异常:[core/not-initialized] Firebase 未正确初始化。您是否将“google-services.json”文件添加到项目中?

main.dart

import 'package:edebiyat_uygulamasi/giris.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(App());


class App extends StatelessWidget 
  // Create the initialization Future outside of `build`:

  @override
  Widget build(BuildContext context) 
    return FutureBuilder(
      // Initialize FlutterFire:
      builder: (context, snapshot) 
        // Check for errors
        if (snapshot.hasError) 
          debugPrint("something went wrong");
        

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) 
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            theme:
                ThemeData(primaryColor: Colors.white, errorColor: Colors.white),
            home: Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: Colors.purple,
              appBar: AppBar(
                title: Text("Engelsiz Edebiyat"),
              ),
              body: GirisSayfasi(),
            ),
          );
        

        // Otherwise, show something whilst waiting for initialization to complete
        return CircularProgressIndicator();
      ,
    );
  

注册屏幕

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';


FirebaseAuth _auth = FirebaseAuth.instance;

String _Email, _Sifre;

class GirisSayfasi extends StatefulWidget 
  @override
  _GirisSayfasiState createState() => _GirisSayfasiState();


class _GirisSayfasiState extends State<GirisSayfasi> 
  @override
  Widget build(BuildContext context) 
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            child: Text(
              "E-posta",
              style: TextStyle(fontSize: 22, color: Colors.white),
            ),
            margin: EdgeInsets.only(top: 30, left: 30),
            alignment: Alignment.topLeft,
          ),
          Container(
            child: TextField(
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  borderSide: BorderSide(color: Colors.white),
                ),
                hintText: "Emailinizi Giriniz",
                hintStyle: TextStyle(color: Colors.white),
              ),
              onChanged: (String edeger) => _Email = edeger,
            ),
            padding: EdgeInsets.only(left: 35, right: 35),
          ),
          Container(
            child: Text(
              "Şifre",
              style: TextStyle(fontSize: 22, color: Colors.white),
            ),
            margin: EdgeInsets.only(top: 30, left: 30),
            alignment: Alignment.topLeft,
          ),
          Container(
            child: TextField(
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  borderSide: BorderSide(color: Colors.white),
                ),
                hintText: " Şifrenizi Giriniz",
                hintStyle: TextStyle(color: Colors.white),
              ),
              onChanged: (String sdeger) => _Sifre = sdeger,
            ),
            padding: EdgeInsets.only(left: 35, right: 35),
          ),
          Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                child: RaisedButton(
                    onPressed: HesapOlustur,
                    child: Text("Hesap Oluştur"),
                    color: Colors.white),
                alignment: Alignment.center,
              ),
            ],
          ),
        ],
      ),
    );
  


HesapOlustur() async 
  UserCredential _credential = await _auth.createUserWithEmailAndPassword(
      email: _Email, password: _Sifre);

pubspec.yaml

name: edebiyat_uygulamasi
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In ios, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^0.18.1+2
  firebase_core: ^0.5.0+1

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  
  # For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

android\buildgradle

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.3'
    


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

android\app\buildgradle

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 from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"


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 "com.example.edebiyat_uygulamasi"
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    

    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 'com.android.support:multidex:1.0.3'


【问题讨论】:

您好,您下载 google-services.json 并将其放在您的 android/app/ 目录中了吗? 您是否尝试过flutter clean 并再次构建您的应用程序? @RatnadeepChakraborty 是的,我下载了 json 文件并将其添加到 android/app 目录 【参考方案1】:

在您的android/app/build.gradle 中输入以下代码,我已添加此行apply plugin: 'com.google.gms.google-services'

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 
    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 "com.example.edebiyat_uygulamasi"
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    

看看它是否有效。

【讨论】:

非常感谢 很高兴,很乐意为您提供帮助。

以上是关于我正在用颤振编写 Firebase 应用程序,但我收到有关 google-services.json 和初始化的错误的主要内容,如果未能解决你的问题,请参考以下文章

使用颤振 firebase_messaging 插件发送通知声音

使用颤振将图像上传并存储到firebase

Firebase Crashlytics/Analytics 不适用于颤振

如何在后台监听firebase实时数据库更新事件并使用颤振自动启动应用程序(如Messenger中的调用功能)?

将数据从 FireBase 检索到颤振项目时出错

在颤振项目中替换 Firebase json 的 Github 操作