4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】「No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() occurred in Instance of xxx 」が発生しFirestoreに接続できない

Last updated at Posted at 2020-10-11

開発環境

  • Flutter: 1.22.0
  • Dart: 2.10.0
  • cloud_firestore: ^0.14.1+3
  • firebase_core: ^0.5.0+1

エラー内容

cloud_firestoreライブラリのFirebaseFirestore.instanceを参照したら下記のエラーが発生した。

Unhandled Exception: Unhandled error [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() occurred in Instance of

エラー文によると、Firebase.initializeApp()を呼べということらしい。

対処法

main.dartにmainメソッド内のrunAppメソッドの前でFirebase.initializeApp()呼ぶ。
initializeAppメソッドは非同期処理なので、awaitキーワードをつけてあげる。
つけないと、Firebaseに接続される前にFirebaseFirestore.instanceを参照して、また同じエラーが発生する可能性がある。

main.dart
Future<void> main() async {
  await Firebase.initializeApp();
  runApp(MyApp());
}

これでビルドしてみる。

別のエラー発生

今度は下記のエラーが発生した。

E/flutter ( 6504): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter ( 6504): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.

今度はWidgetsFlutterBinding.ensureInitialized()メソッドを呼べということらしい。

下記、ensureInitializedメソッドの公式ドキュメントから引用する。

Returns an instance of the WidgetsBinding, creating and initializing it if necessary. If one is created, it will be a WidgetsFlutterBinding. If one was previously initialized, then it will at least implement WidgetsBinding.

You only need to call this method if you need the binding to be initialized before calling runApp.

In the flutter_test framework, testWidgets initializes the binding instance to a TestWidgetsFlutterBinding, not a WidgetsFlutterBinding.

runAppメソッドの前に非同期の処理を実行する際はこのメソッドを使え、と無理やり解釈する。

ということでFirebase.initializeApp()メソッドの前に、WidgetsFlutterBinding.ensureInitialized()を実行する。

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

これでようやくエラーが消えた。
めでたしめでたし。

参考

4
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?