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

Firebase导致Flutter应用在自身库代码处构建崩溃

Flutter Firebase 构建崩溃问题

操作流程

在全新Flutter项目中重复执行以下步骤仍出现问题:

  • 在项目根目录执行命令:
    flutterfire configure
    
  • 选择目标Firebase项目,勾选Android、iOS、macOS、Web所有平台,同意更新android/build.gradle和android/app/build.gradle。
  • 操作完成后收到提示:

    Firebase configuration file lib/firebase_options.dart generated successfully with the following Firebase apps:

问题现象

仅导入以下两个库就导致构建崩溃:

import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

错误信息

: Error: '$throw' isn't a type.
../…/method_channel/method_channel_firebase.dart:120
        $throw coreNotInitialized();
        ^^^^^^
: Error: Expected ';' after this.
../…/method_channel/method_channel_firebase.dart:120
        $throw coreNotInitialized();
               ^^^^^^^^^^^^^^^^^^
: Error: Expected an identifier, but got ')'.
../…/method_channel/method_channel_firebase.dart:120
Try inserting an identifier before ')'.

        $throw coreNotInitialized();
                                  ^

示例代码

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text("My App")),
        body: const Center(child: Text("MyApp")),
      ),
    );
  }
}

解决方法

  • 检查版本兼容性
    打开pubspec.yaml,确保firebase_core版本与当前Flutter SDK匹配。执行flutter pub outdated查看版本冲突,指定兼容的稳定版本后执行flutter pub get,示例:

    dependencies:
      firebase_core: ^2.15.0 # 替换为对应Flutter版本的稳定兼容版
    
  • 清理项目缓存
    依次执行以下命令:

    flutter clean
    rm pubspec.lock
    flutter pub get
    

    若为Android项目,进入android目录执行./gradlew clean。

  • 检查Dart版本
    通过dart --version查看版本,确保版本符合Firebase库要求,若过低则升级至Flutter SDK对应的稳定版Dart。

  • 临时修复文件
    找到报错的method_channel_firebase.dart文件,将$throw coreNotInitialized();修改为throw coreNotInitialized();(去掉$符号),保存后重新构建。此为临时方案,更新依赖后需重新检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:50:43