Jonny
Jonny

Reputation: 306

Flutter FirebaseFirestore multiple apps

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++;
    });
  }

Upvotes: 2

Views: 1578

Answers (2)

rouatbi ahmed
rouatbi ahmed

Reputation: 1

If however you'd like to use Firestore with a secondary Firebase App, use the instanceFor method:

FirebaseApp secondaryApp = Firebase.app('SecondaryApp');
FirebaseFirestore firestore = FirebaseFirestore.instanceFor(app: secondaryApp);

for more information you check this link : https://firebase.flutter.dev/docs/firestore/usage/

Upvotes: 0

Booyah
Booyah

Reputation: 111

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[].

Upvotes: 3

Related Questions