is it ok to call firebase.initializeApp() in the main

Viewed 4598

flutterfire recently introduced some changes and one of those is the need to call initializeApp() before using any plugin.

is it ok to call it in the main ? something like this :

void main() async {
  await Firebase.initializeApp();
  return runApp(App());
}

or maybe like this without async await

void main() {
  Firebase.initializeApp();
  return runApp(App());
}

i think the first example is more correct but its blocking the execution of the main and i have no idea how much time before the future complete?

1 Answers

The only requirement from Firebase is that you call Firebase.initializeApp() before any other Firebase APIs are called. If that condition isn't met, it will raise an exception explicitly telling you so.

In my code I call it in my main, which is the earliest place I can think if, and it works without problems:

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

The initialization of Firebase at this level is pretty much instantaneous, as it's just waiting for the call to the native code to complete, and the native code itself does nothing more then look up the configuration values.

But if that is taking too long for you, you can call it without await. It just means that you may have to deal with that Future<FirebaseApp> later in your code where you access Firebase.

Related