Search code examples
iosflutterfirebasegoogle-cloud-firestore

Use Firestore in both Flutter module and native iOS


We have a native iOS app and we're migrating it to Flutter incrementally as rewriting the entire app in Flutter is not viable at the moment. We heavily depend upon Firebase resources, such as auth, Firestore, etc. and we need to use them both in native code and Flutter code.

We were able to initialize the Firebase instance in Flutter:

final app = await Firebase.initializeApp();

As well as get the current user, which was authenticated by the native code, from Firebase auth:

final userId = FirebaseAuth.instance.currentUser?.uid;

However, we are not able to access Firestore:

final users = await FirebaseFirestore.instance.collection('users').get();

Whenever we try that, we get an error:

Terminating app due to uncaught exception 'FIRIllegalStateException', reason: 'Firestore instance has already been started and its settings can no longer be changed. You can only set settings before calling any other methods on a Firestore instance.'

It seems the FLTFirebaseFirestorePlugin is trying to redefine the settings of the current Firestore instance:

FIRFirestore *firestore = [FIRFirestore firestoreForApp:app database:databaseUrl];
firestore.settings = settings;

We tried many things but can't get past that error.

Has anyone been able to use Firestore in both Flutter module and native iOS?

Or is there any workaround that could be applied?


Found the exact same issue here, with no response: Initialize and use Firestore in both native iOS and Flutter

Also reported in this GH ticket: https://github.com/firebase/flutterfire/issues/9582


Solution

  • Looks like Firebase and Firestore have already created an App instance named DEFAULT on the iOS native side, and cannot recreate a new Firestore instance when you call FirebaseFirestore.instance.collection('users').get();

    I suggest you create another instance in Flutter by passing a name variable by initializing Firebase in Flutter like this:

    final app = await Firebase.initializeApp(name: "ANOTHER_INSTANCE");