Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 [cloud_firestore] database is locked (Sqlite code 5 SQLITE_BUSY) #6087

Closed
otopba opened this issue May 9, 2021 · 21 comments · May be fixed by #8061
Closed

🐛 [cloud_firestore] database is locked (Sqlite code 5 SQLITE_BUSY) #6087

otopba opened this issue May 9, 2021 · 21 comments · May be fixed by #8061
Assignees
Labels

Comments

@otopba
Copy link

otopba commented May 9, 2021

Bug report

I have bug reports in my crashlytics:

Fatal Exception: java.lang.RuntimeException
Internal error in Cloud Firestore (22.0.1).
com.google.firebase.firestore.util.AsyncQueue.b (AsyncQueue.java:19)
com.google.firebase.firestore.util.AsyncQueue$$Lambda$3.run (AsyncQueue.java:2)
android.os.Handler.handleCallback (Handler.java:888)
android.os.Handler.dispatchMessage (Handler.java:100)
android.os.Looper.loop (Looper.java:213)
android.app.ActivityThread.main (ActivityThread.java:8178)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:513)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1101)
Caused by java.lang.RuntimeException
android.database.sqlite.SQLiteDatabaseLockedException: database is locked (Sqlite code 5 SQLITE_BUSY), (OS error - 11:Try again)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor.a (AsyncQueue.java:14)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$$Lambda$2.run (AsyncQueue.java:4)
java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:462)
java.util.concurrent.FutureTask.run (FutureTask.java:266)
java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run (ScheduledThreadPoolExecutor.java:301)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$DelayedStartFactory.run (AsyncQueue.java:15)
java.lang.Thread.run (Thread.java:929)
Caused by android.database.sqlite.SQLiteDatabaseLockedException
database is locked (Sqlite code 5 SQLITE_BUSY), (OS error - 11:Try again)
android.database.sqlite.SQLiteConnection.nativeExecute (SQLiteConnection.java)
android.database.sqlite.SQLiteConnection.execute (SQLiteConnection.java:694)
android.database.sqlite.SQLiteSession.beginTransactionUnchecked (SQLiteSession.java:335)
android.database.sqlite.SQLiteSession.beginTransaction (SQLiteSession.java:310)
android.database.sqlite.SQLiteDatabase.beginTransaction (SQLiteDatabase.java:595)
android.database.sqlite.SQLiteDatabase.beginTransactionWithListener (SQLiteDatabase.java:558)
com.google.firebase.firestore.local.SQLitePersistence.a (SQLitePersistence.java:17)
com.google.firebase.firestore.local.LocalStore.startMutationQueue (LocalStore.java:8)
com.google.firebase.firestore.local.LocalStore.start (LocalStore.java)
com.google.firebase.firestore.core.ComponentProvider.initialize (ComponentProvider.java:43)
com.google.firebase.firestore.core.FirestoreClient.a (FirestoreClient.java:65)
com.google.firebase.firestore.core.FirestoreClient.a (FirestoreClient.java:10)
com.google.firebase.firestore.core.FirestoreClient$$Lambda$1.run (FirestoreClient.java:8)
com.google.firebase.firestore.util.AsyncQueue.lambda$enqueue$2 (AsyncQueue.java)
com.google.firebase.firestore.util.AsyncQueue$$Lambda$2.call (AsyncQueue.java:2)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor.access$100 (AsyncQueue.java)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$$Lambda$2.run (AsyncQueue.java:4)
java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:462)
java.util.concurrent.FutureTask.run (FutureTask.java:266)
java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run (ScheduledThreadPoolExecutor.java:301)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$DelayedStartFactory.run (AsyncQueue.java:15)

image

Steps to reproduce

I don't know. But every crash was when the app was in the background

Flutter doctor

Click To Expand
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel dev, 2.3.0-0.1.pre, on macOS 11.3 20E232 darwin-x64, locale en-RU)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2021.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2021.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2020.3.3)
[✓] VS Code (version 1.55.2)
[✓] Connected device (2 available)

• No issues found!


Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand
Dart SDK 2.14.0-18.0.dev
Flutter SDK 2.3.0-0.1.pre
word_daily 0.1.2+75

dependencies:
- amplitude_flutter 3.1.0 [flutter]
- another_flushbar 1.10.20 [pedantic flutter]
- async 2.5.0 [collection]
- built_value 8.0.5 [built_collection collection fixnum]
- cached_network_image 3.0.0 [flutter flutter_cache_manager octo_image]
- cloud_firestore 1.0.7 [cloud_firestore_platform_interface cloud_firestore_web firebase_core firebase_core_platform_interface flutter meta]
- cloud_functions 1.0.5 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter]
- cupertino_icons 1.0.3
- firebase_analytics 8.0.2 [firebase_analytics_platform_interface firebase_analytics_web firebase_core flutter meta]
- firebase_auth 1.1.2 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 1.1.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 2.0.2 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_dynamic_links 2.0.2 [firebase_core flutter]
- firebase_messaging 9.1.3 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_remote_config 0.6.0 [flutter firebase_core]
- flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine]
- flutter_email_sender 5.0.0 [flutter]
- flutter_inapp_purchase 5.0.1 [http meta flutter platform]
- flutter_local_notifications 5.0.0+3 [flutter flutter_local_notifications_platform_interface platform timezone]
- flutter_phoenix 1.0.0 [flutter]
- flutter_svg 0.22.0 [flutter meta path_drawing vector_math xml]
- google_sign_in 5.0.2 [google_sign_in_platform_interface google_sign_in_web flutter meta]
- horizontal_blocked_scroll_physics 3.0.0 [flutter pedantic]
- intl 0.17.1-nullsafety.3 [clock path]
- intl_translation 0.17.10+1 [analyzer args dart_style intl path petitparser]
- launch_options 0.0.1 [flutter]
- mime 1.0.0
- optimist_dev_common 1.6.1 [flutter http intl share json_api built_value f_logs strings]
- package_info 2.0.0 [flutter]
- permission_handler 7.1.0 [flutter meta permission_handler_platform_interface]
- provider 5.0.0 [collection flutter nested]
- pull_to_refresh 1.6.5 [flutter]
- scroll_to_index 2.0.0 [flutter]
- share 2.0.1 [meta mime flutter]
- shared_preferences 2.0.5 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows]
- sign_in_with_apple 3.0.0 [flutter meta]
- url_launcher 5.7.10 [flutter url_launcher_platform_interface url_launcher_web url_launcher_linux url_launcher_macos url_launcher_windows]
- url_launcher_web 0.1.5+3 [url_launcher_platform_interface flutter flutter_web_plugins meta]
- video_player 2.1.1 [meta video_player_platform_interface video_player_web flutter flutter_test]
- visibility_detector 0.2.0 [flutter]
- vk_bridge 1.3.0 [js built_value built_collection rxdart meta]
- wakelock 0.5.1 [flutter meta wakelock_macos wakelock_platform_interface wakelock_web wakelock_windows]
- workmanager 0.4.0 [flutter]

dev dependencies:
- build_runner 1.12.2 [args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style glob graphs http_multi_server io js logging meta mime path pedantic pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- built_value_generator 8.0.5 [analyzer build build_config built_collection built_value source_gen quiver]
- cloud_firestore_mocks 0.8.2 [flutter cloud_firestore cloud_firestore_platform_interface collection plugin_platform_interface mockito quiver]
- flutter_launcher_icons 0.9.0 [args image path yaml]
- flutter_localizations 0.0.0 [flutter intl characters clock collection meta path typed_data vector_math]
- flutter_native_splash 1.1.8+4 [image meta path xml yaml universal_io]
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data]
- mockito 5.0.7 [analyzer build code_builder collection dart_style matcher meta path source_gen test_api]

dependency overrides:
- analyzer 1.5.0 [_fe_analyzer_shared cli_util collection convert crypto glob meta package_config path pub_semver source_span watcher yaml pedantic]
- args 2.1.0
- firebase_core 1.1.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- http 0.13.3 [async http_parser meta path pedantic]
- http_parser 4.0.0 [charcode collection source_span string_scanner typed_data]
- intl 0.17.1-nullsafety.3 [clock path]
- path_provider 2.0.1 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows]
- petitparser 4.1.0 [meta]
- plugin_platform_interface 2.0.0 [meta]

transitive dependencies:
- _fe_analyzer_shared 21.0.0 [meta]
- archive 3.1.2 [crypto path]
- boolean_selector 2.1.0 [source_span string_scanner]
- build 2.0.1 [analyzer async convert crypto glob logging meta path]
- build_config 0.4.7 [checked_yaml json_annotation meta path pubspec_parse yaml]
- build_daemon 2.1.10 [built_collection built_value http_multi_server logging pedantic path pool shelf shelf_web_socket stream_transform watcher web_socket_channel]
- build_resolvers 2.0.0 [analyzer build crypto graphs logging path package_config pool pub_semver stream_transform]
- build_runner_core 6.1.12 [async build build_config build_resolvers collection convert crypto glob graphs logging meta path package_config pedantic pool timing watcher yaml]
- built_collection 5.0.0
- characters 1.1.0
- charcode 1.2.0
- checked_yaml 2.0.1 [json_annotation source_span yaml]
- cli_util 0.3.0 [meta path]
- clock 1.1.0
- cloud_firestore_platform_interface 4.0.3 [collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 1.0.7 [cloud_firestore_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- cloud_functions_platform_interface 5.0.3 [firebase_core flutter meta plugin_platform_interface]
- cloud_functions_web 4.0.5 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- code_builder 3.7.0 [built_collection built_value collection matcher meta]
- collection 1.15.0
- convert 3.0.0 [typed_data]
- crypto 3.0.1 [collection typed_data]
- dart_style 1.3.14 [analyzer args path pub_semver source_span]
- f_logs 2.0.0 [flutter sembast path_provider intl xxtea meta path stack_trace]
- fake_async 1.2.0 [clock collection]
- ffi 1.0.0
- file 6.1.0 [meta path]
- firebase 9.0.1 [http http_parser js]
- firebase_analytics_platform_interface 2.0.0 [flutter meta]
- firebase_analytics_web 0.3.0 [firebase firebase_analytics_platform_interface flutter flutter_web_plugins meta]
- firebase_auth_platform_interface 4.2.0 [firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 1.1.0 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta]
- firebase_core_platform_interface 4.0.0 [flutter meta plugin_platform_interface]
- firebase_core_web 1.0.2 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_crashlytics_platform_interface 3.0.2 [collection firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_platform_interface 2.1.3 [firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 1.0.6 [firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- fixnum 1.0.0
- flutter_blurhash 0.6.0 [flutter meta pedantic]
- flutter_cache_manager 3.0.1 [clock collection file flutter http image path path_provider pedantic rxdart sqflite uuid]
- flutter_local_notifications_platform_interface 3.0.0 [flutter plugin_platform_interface]
- flutter_web_plugins 0.0.0 [flutter js characters collection meta typed_data vector_math]
- glob 2.0.1 [async collection file path pedantic string_scanner]
- google_sign_in_platform_interface 2.0.1 [flutter meta quiver]
- google_sign_in_web 0.10.0 [google_sign_in_platform_interface flutter flutter_web_plugins meta js]
- graphs 1.0.0
- http_multi_server 3.0.1 [async]
- image 3.0.2 [archive meta xml]
- io 1.0.0 [meta path string_scanner]
- js 0.6.3
- json_annotation 4.0.1
- json_api 4.3.0 [http http_parser]
- lists 1.0.0 [meta]
- logging 1.0.1
- matcher 0.12.10 [stack_trace]
- meta 1.3.0
- nested 1.0.0 [flutter]
- octo_image 1.0.0+1 [flutter flutter_blurhash]
- package_config 2.0.0 [path]
- path 1.8.0
- path_drawing 0.5.0 [vector_math meta path_parsing flutter]
- path_parsing 0.2.0 [vector_math meta]
- path_provider_linux 2.0.0 [path xdg_directories path_provider_platform_interface flutter]
- path_provider_macos 2.0.0 [flutter]
- path_provider_platform_interface 2.0.1 [flutter meta platform plugin_platform_interface]
- path_provider_windows 2.0.1 [path_provider_platform_interface meta path flutter ffi win32]
- pedantic 1.11.0
- permission_handler_platform_interface 3.3.0 [flutter meta plugin_platform_interface]
- platform 3.0.0
- pool 1.5.0 [async stack_trace]
- process 4.2.1 [file path platform]
- pub_semver 2.0.0 [collection]
- pubspec_parse 1.0.0 [checked_yaml collection json_annotation pub_semver yaml]
- quiver 3.0.1 [matcher]
- rxdart 0.26.0
- sembast 3.0.2 [meta path synchronized pedantic]
- shared_preferences_linux 2.0.0 [flutter file meta path path_provider_linux shared_preferences_platform_interface]
- shared_preferences_macos 2.0.0 [shared_preferences_platform_interface flutter]
- shared_preferences_platform_interface 2.0.0 [flutter]
- shared_preferences_web 2.0.0 [shared_preferences_platform_interface flutter flutter_web_plugins meta]
- shared_preferences_windows 2.0.0 [shared_preferences_platform_interface flutter file meta path path_provider_platform_interface path_provider_windows]
- shelf 1.1.1 [async collection http_parser path stack_trace stream_channel]
- shelf_web_socket 1.0.1 [shelf stream_channel web_socket_channel]
- sky_engine 0.0.99
- source_gen 0.9.10+4 [analyzer async build dart_style glob meta path pedantic source_span]
- source_span 1.8.1 [collection path term_glyph]
- sqflite 2.0.0+3 [flutter sqflite_common path]
- sqflite_common 2.0.0+2 [synchronized path meta]
- stack_trace 1.10.0 [path]
- stream_channel 2.1.0 [async]
- stream_transform 2.0.0
- string_scanner 1.1.0 [charcode source_span]
- strings 0.2.1 [characters unicode]
- synchronized 3.0.0
- term_glyph 1.2.0
- test_api 0.3.0 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher]
- timezone 0.7.0 [path]
- timing 1.0.0 [json_annotation]
- typed_data 1.3.0 [collection]
- unicode 0.3.0 [lists]
- universal_io 2.0.4 [collection crypto meta typed_data]
- url_launcher_linux 0.0.1+4 [flutter]
- url_launcher_macos 0.0.1+9 [flutter]
- url_launcher_platform_interface 1.0.9 [flutter meta plugin_platform_interface]
- url_launcher_windows 0.0.1+3 [flutter]
- uuid 3.0.4 [crypto]
- vector_math 2.1.0
- video_player_platform_interface 4.1.0 [flutter meta flutter_test]
- video_player_web 2.0.0 [flutter flutter_web_plugins meta video_player_platform_interface]
- wakelock_macos 0.1.0 [flutter flutter_web_plugins wakelock_platform_interface]
- wakelock_platform_interface 0.2.0 [flutter meta]
- wakelock_web 0.2.0 [flutter flutter_web_plugins js wakelock_platform_interface]
- wakelock_windows 0.1.0 [flutter wakelock_platform_interface win32]
- watcher 1.0.0 [async path pedantic]
- web_socket_channel 2.1.0 [async crypto stream_channel]
- win32 2.0.5 [ffi]
- xdg_directories 0.2.0 [meta path process]
- xml 5.1.0 [collection meta petitparser]
- xxtea 2.1.0
- yaml 3.1.0 [collection source_span string_scanner]

@otopba otopba added Needs Attention This issue needs maintainer attention. type: bug Something isn't working labels May 9, 2021
@markusaksli-nc markusaksli-nc added triage Issue is currently being triaged. plugin: cloud_firestore type: crash A compile error or crash and removed Needs Attention This issue needs maintainer attention. triage Issue is currently being triaged. type: bug Something isn't working labels May 11, 2021
@GokayFinfree
Copy link

Hi @otopba,
Having the same problem with 23.0.0 instead of 22.0.1, did you find any solution about it, or maybe what causing it?

@otopba
Copy link
Author

otopba commented Jun 9, 2021

Hi @otopba,
Having the same problem with 23.0.0 instead of 22.0.1, did you find any solution about it, or maybe what causing it?

Hi!
I think that the problem is in using this library from several isolates. I haven't found a solution. Do you have one isolate in your application?

@GokayFinfree
Copy link

No, but my app uses streams and async code heavily, async queue keyword in stack trace makes me wonder if I missing some await keyword somewhere.

@ssabbarw
Copy link

ssabbarw commented Jul 14, 2021

I had raised #6592 regarding same issue. All crashes that i have checked occur when user is interacting with the notification(which i am sending via scheduled FCM notification). But i have also seen crashes where there was nothing in crashlytics logs
069665B2-4DBA-4D17-A2B6-0B6520487E75
5E490BDD-0A3B-4EB8-ABF1-3350B6E3E025
A4D109C8-DC99-40D8-A454-DC2308D0EE1D
397B0E15-CCEC-40C3-BE2C-6FD2E7A2894A

@ssabbarw
Copy link

I think this is caused when we try to initialise multiple firebase apps. I was initialising firebase app in main method of my flutter app and on onBackgroundMessage that i register with FIrebaseCloudMessage service. I removed it from onBackgroundMessage and i have not seen a single crash in last 2 days. I think i saw this msg in crash logs that it maybe due to multiple firebase app initialising. But since crashes are so many i could not find the message again to paste it here.

The error message should be more clear here.
Will update this if i see same crash again.

@ssabbarw
Copy link

Confirming that i have not seen this crash after i removed initialising firebase app second time in my code.
But error msg should be more clear.
Thanks for the help.

@russellwheatley
Copy link
Member

@otopba, are you able to confirm if you are also initialising Firebase in the onBackgroundMessage handler? The SQLLite error you're receiving is because there is a concurrent database connection which might be a result of two instances of Firestore.

Or at least, that appears to be what happened with @ssabbarw.

@otopba
Copy link
Author

otopba commented Sep 1, 2021

@otopba, are you able to confirm if you are also initialising Firebase in the onBackgroundMessage handler? The SQLLite error you're receiving is because there is a concurrent database connection which might be a result of two instances of Firestore.

Or at least, that appears to be what happened with @ssabbarw.

Yes, that seems to be the problem. The crash happens some time after the user receives the notification via onBackgroundMessage

@russellwheatley russellwheatley self-assigned this Sep 1, 2021
@atrope
Copy link
Contributor

atrope commented Sep 3, 2021

I Can also confirm this was happening with our app.
Removed Firebase init from onBackgroundMessage and solved the issue.

@ViniciusSossela
Copy link

Removing Firebase init from onBackgroundMessage doesn't compromise the functionality? For example, we are querying Firestore docs onBackgroundMessage... it will keep working without initializing Firebase?

@najibghadri
Copy link

najibghadri commented Jan 22, 2022

Hello! I get the same problem, here is a link to our sentry log: https://sentry.io/share/issue/3aad3b8795e042419857027891827607/

I am also using Firebase in the onBackgroundMessage. This happens when the app is not running in the background, and I get a notification.

@najibghadri
Copy link

najibghadri commented Jan 22, 2022

I think I got a fix!
Instead of calling init in multiple places (onBackgroundMsg, main), do this:
Make initializeApp future global:

final firebaseInit =
    Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // (I am using dart-only init)

And await firebaseInit wherever you need it.
I think what happens is dart reuses the same isolate as the background msg when it starts up.

@russellwheatley
Copy link
Member

russellwheatley commented Jan 25, 2022

Hey @najibghadri, thanks for the feedback! @otopba are you or anyone else experiencing the problem able to confirm this behaviour?

@otopba
Copy link
Author

otopba commented Jan 25, 2022

@russellwheatley I will try in next release

@otopba
Copy link
Author

otopba commented Feb 1, 2022

@russellwheatley Yes, that helped. The error no longer appears

@russellwheatley
Copy link
Member

Hey @najibghadri @otopba, just to be clear, this is the setup you're referring to?

Future<FirebaseApp> init() {
  return Firebase.initializeApp(options: DefaultFirebaseConfig.platformOptions);
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await init();
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await init();
  
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  
  runApp(MessagingExampleApp());
}

I'm looking to update documentation and example app with the latest setup. Thanks.

@najibghadri
Copy link

najibghadri commented Feb 8, 2022

No @russellwheatley this is still gonna call initializeApp as many times as you call init().
This is my solution:

final firebaseInit =
    Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

// and then await firebaseInit; wherever you want
...
await firebaseInit;
...

It's a call to initializeApp once globally, and then await firebaseInit. This ensures initializeApp is called once, and you can await the completed future from wherever, any number of times

@najibghadri
Copy link

najibghadri commented Feb 8, 2022

So your solution is this instead:

final init = Firebase.initializeApp(options: DefaultFirebaseConfig.platformOptions);

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await init;
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await init;
  
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  
  runApp(MessagingExampleApp());
}

@najibghadri
Copy link

You could say it's a drawback to have a global call to initializeApp, if you don't like this you can implement a proxy that checks if it has been called already, if not it does call initApp

@najibghadri
Copy link

But the real solution would be if this is fixed on the Firebase level, it shouldn't fail on a repeated call.

@otopba
Copy link
Author

otopba commented Feb 11, 2022

@russellwheatley Hi!

In my project I did this:

class FirebaseService {
  FirebaseService._();

  static final instance = FirebaseService._();
  Completer? _completer;

  Future<void> init() async {
    Completer? completer = _completer;
    if (completer == null) {
      completer = Completer();
      _completer = completer;
      _initInternal();
    }
    return completer.future;
  }

  void _initInternal() async {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "XXX",
        authDomain: "XXX",
        databaseURL: "XXX",
        projectId: "XXX",
        storageBucket: "XXX",
        messagingSenderId: "XXX",
        appId: "XXX",
        measurementId: "XXX",
      ),
    );
    _completer!.complete();
  }
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    await FirebaseService.instance.init();
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FirebaseService.instance.init();
  
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  
  runApp(App());
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
10 participants