You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Flutter项目中的'FirebaseCoreHostApi.optionsFromResource'错误?

Flutter Firebase初始化错误问题及解决方案

问题详情

我在Flutter项目中初始化Firebase时一直报错,相关代码和配置如下:

主Dart文件

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();

pubspec.yaml依赖项

dependencies:
geolocator: ^9.0.2
flutter:
 sdk: flutter
intl: any
firebase_core: any
firebase_auth: any
cloud_firestore: any
firebase_analytics: any
firebase_core_platform_interface: any
flutter_local_notifications: any
shared_preferences: any
device_info: any
table_calendar: any
flutter_datetime_picker: any
geocoding: any
cupertino_icons: any
location: any
permission_handler: any
google_maps_flutter: any
firebase_database: any
excel: any
path_provider: any

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

android {
compileSdkVersion 33
buildToolsVersion "33.0.0"
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 {
        minSdkVersion 20
        multiDexEnabled true
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.picar_dlava"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        targetSdkVersion flutter.targetSdkVersion
        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 'androidx.multidex:multidex:2.0.1'
implementation platform('com.google.firebase:firebase-bom:32.0.0')
implementation 'com.google.firebase:firebase-analytics:17.5.0'
}

android/build.gradle配置

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

    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.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')
}

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

错误日志

n value., null, null)
E/flutter (12308): #0      FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:248:7)
E/flutter (12308): <asynchronous suspension>
E/flutter (12308): #1      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89:25)
E/flutter (12308): <asynchronous suspension>
E/flutter (12308): #2      Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:31)
E/flutter (12308): <asynchronous suspension>
E/flutter (12308): #3      main (package:picagem_dalva/main.dart:14:3)
E/flutter (12308): <asynchronous suspension>
E/flutter (12308):

已尝试操作

  • 移动google-services.json文件,但问题未解决

解决步骤

  1. 检查google-services.json的有效性

    • 确保文件放在android/app/目录下,文件名完全为google-services.json,无拼写错误
    • 核对文件里的package_name和app/build.gradle中的applicationId(即com.example.picar_dlava)是否一致,不一致会导致初始化失败
  2. 完善app/build.gradle配置

    • 在app/build.gradle的末尾添加一行:apply plugin: 'com.google.gms.google-services',根build.gradle已经引入了插件,但app模块没应用,这会导致google-services.json无法被识别
  3. 修复依赖版本问题

    • 避免用any指定版本,这容易引发依赖冲突,改用具体稳定版本,同时移除不需要的间接依赖,修改后的pubspec.yaml依赖如下:
      dependencies:
        geolocator: ^9.0.2
        flutter:
          sdk: flutter
        intl: ^0.18.1
        firebase_core: ^2.15.0
        firebase_auth: ^4.10.0
        cloud_firestore: ^4.9.0
        firebase_analytics: ^10.4.0
        flutter_local_notifications: ^16.1.0
        shared_preferences: ^2.2.2
        device_info_plus: ^9.1.0  # 原device_info已废弃,替换为这个
        table_calendar: ^3.0.9
        flutter_datetime_picker: ^1.5.1
        geocoding: ^2.1.1
        cupertino_icons: ^1.0.6
        location: ^5.0.3
        permission_handler: ^10.2.0
        google_maps_flutter: ^2.5.0
        firebase_database: ^10.3.0
        excel: ^4.0.0
        path_provider: ^2.1.1
      
    • 删除firebase_core_platform_interface的直接依赖,它是firebase_core的间接依赖,不需要单独声明
  4. 清理并重新构建项目

    • 依次执行以下命令:
      flutter clean
      flutter pub get
      cd android && ./gradlew clean
      cd .. && flutter run
      
  5. 显式传入FirebaseOptions(备选方案)

    • 如果以上步骤都无效,直接在初始化代码里传入Firebase配置信息,这些信息可以从google-services.json里提取:
      void main() async {
        WidgetsFlutterBinding.ensureInitialized();
        await Firebase.initializeApp(
          options: FirebaseOptions(
            apiKey: "你的API_KEY",
            appId: "你的APP_ID",
            messagingSenderId: "你的SENDER_ID",
            projectId: "你的PROJECT_ID",
            storageBucket: "你的STORAGE_BUCKET",
          ),
        );
        runApp(MyApp());
      }
      

内容的提问来源于stack exchange,提问作者Hugo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:40:04