Flutter FirebaseFirestore multiple apps

Viewed 495

Im working on a flutter project, when i'm trying to connect to Firestore using a secondary firebase app. see Configure multiple projects.

I get the following error when trying to connect to db

secAppFirestore
        .collection("yos")

:

"Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp".

my code

void main() async {
  // Avoid errors caused by flutter upgrade.
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    name: "yostest2-xxxxx",
    options: FirebaseOptions(
      apiKey: "AIzaSy...",
      appId: "1:68080...",
      messagingSenderId: "",
      projectId: "yostest2-xxxxx",
      storageBucket: "yostest2-xxxxx.appspot.com",
      databaseURL: 'https://yostest2-xxxxx.firebaseio.com',
    ),
  );

  runApp(const MyApp());
}

....

 void _incrementCounter() async {
    FirebaseApp secondaryApp = Firebase.app('yostest2-xxxxx');
    FirebaseFirestore secAppFirestore =
        FirebaseFirestore.instanceFor(app: secondaryApp);
    await secAppFirestore
        .collection("yos")
        .add({"timestamp": FieldValue.serverTimestamp()});

    setState(() {
      _counter++;
    });
  }
1 Answers

You need to call Firebase.initializeApp(); which will initialize the default app before you call Firebase.initializeApp(name: "yostest2-xxxxx",...) for your secondary app. Place it above your current init line and await it as well.

If you encounter issues on hot reload then you may also have to track whether initializeApp has already been called via iterating Firebase.apps[].

Related