# FirebaseException：Firebase 未初始化。请确保在使用任何 Firebase 服务之前调用 Firebase.initializeApp()。

- **ID:** `flutter/firebase-initialization-race`
- **领域:** flutter
- **类别:** runtime_error
- **错误码:** `FIREBASE_NOT_INITIALIZED`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

在 Firebase.initializeApp() 完成之前调用了 Firebase 服务方法，通常是由于异步初始化中的竞态条件。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.22.0 | active | — | — |
| firebase_core 2.24.0 | active | — | — |
| firebase_auth 4.16.0 | active | — | — |

## 解决方案

1. ```
   Ensure Firebase.initializeApp() is called at the top level of main.dart before runApp(). Use await and wrap in a try-catch. Example: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
   ```
2. ```
   Use a FutureBuilder or a splash screen that waits for initialization. Example: FutureBuilder(future: Firebase.initializeApp(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return MyApp(); } else { return SplashScreen(); } })
   ```
3. ```
   If using multiple Firebase instances, call Firebase.initializeApp() with the specific options for each instance before accessing their services.
   ```

## 无效尝试

- **Call Firebase.initializeApp() synchronously by removing async/await.** — Firebase.initializeApp() is inherently asynchronous; removing await causes it to return a Future that may not complete before service calls. (95% 失败率)
- **Move Firebase.initializeApp() to the initState() of every widget that uses Firebase.** — Multiple calls to initializeApp() are not harmful but do not guarantee the timing; the race condition persists if widgets initialize independently. (80% 失败率)
