Flutter - 尝试使用默认设置初始化 Firebase 时出错

Flutter - Errors when trying to intialize Firebase with default settings

之前,我在尝试从我之前的 Flutter 项目复制代码时遇到此 错误,这要求我在 firebase_core 和 运行 Firebase.initializeApp() 之前导入=12=].

不幸的是,我在尝试正确遵循此处的安装说明时出现以下错误 https://pub.dev/packages/firebase_core,这是由于这两行中无法解析的引用引起的

import 'package:firebase_core_example/firebase_config.dart'

FirebaseApp app = await Firebase.initializeApp(options : DefaultFirebaseConfig.platformOptions)

所以我想知道 firebase_core_example 和它的 DefaultFirebaseConfig class 实际上是从哪里来的,因为我找不到 pub.dev 的任何地方。当然应该允许默认设置,因为所有必需的信息都已包含在 android/app/google-services.json 文件中。我认为我不需要在 Dart 文件中再次对其进行硬编码。

DefaultFirebaseConfig 是一个自定义 class,它包含每个平台的 FirebaseOptions

import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';

class DefaultFirebaseConfig {
  static FirebaseOptions get platformOptions {
    if (kIsWeb) {
      // Web
      return const FirebaseOptions(
        appId: '1:448618578101:web:0b650370bb29e29cac3efc',
        apiKey: 'AIzaSyAgUhHU8wSJgO5MVNy95tMT07NEjzMOfz0',
        projectId: 'react-native-firebase-testing',
        messagingSenderId: '448618578101',
      );
    } else if (Platform.isIOS || Platform.isMacOS) {
      // iOS and MacOS
      return const FirebaseOptions(
        appId: '1:448618578101:ios:0b650370bb29e29cac3efc',
        apiKey: 'AIzaSyAgUhHU8wSJgO5MVNy95tMT07NEjzMOfz0',
        projectId: 'react-native-firebase-testing',
        messagingSenderId: '448618578101',
        iosBundleId: 'io.flutter.plugins.firebasecoreexample',
      );
    } else {
      // Android
      return const FirebaseOptions(
        appId: '1:448618578101:android:0446912d5f1476b6ac3efc',
        apiKey: 'AIzaSyCuu4tbv9CwwTudNOweMNstzZHIDBhgJxA',
        projectId: 'react-native-firebase-testing',
        messagingSenderId: '448618578101',
      );
    }
  }
}

如果您只针对 Android 平台并添加了 google-services.json 文件,那么您可以这样做:

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

没有提供 FirebaseOptions 参数。

Peter Haddad 的回答应该有效,但不幸的是,在我的情况下,它产生了这个运行时错误,我不知道为什么。

Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized. Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp. View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

所以我只是按照 link 继续安装 Firebase 和 FlutterFire 的 CLI。 flutterfire configure 生成了 firebase_options.dart 文件,其内容与上述答案类似,只是 class.getter 名称更改为 DefaultFirebaseOptions.currentPlatform,因此我仍然必须使用选项参数 Firebase.initializeApp(options : DefaultFirebaseOptions.currentPlatform) 初始化 Firebase ]