mobix
mobix

Reputation: 515

Add two different Firebase projects to my Flutter project

I've created a flutter project 'example', and i want to add to firebase projects 'fire1' and 'fire2'. in the normal way adding firebase is by adding google-services.json and GoogleServices-Info.plist for IOS and Android. so how can I add two firebase in one flutter project?

Upvotes: 18

Views: 8516

Answers (4)

Md Wasim Reza Ali
Md Wasim Reza Ali

Reputation: 11

Initialize Two Firebase Apps in iOS:

Step 1: Initialize the Default app in Flutter main file

Step 2: Initialize the second firebase app manually in appdelegate file no googlejsoninfo.plist needed for the second app in the app directory.

import UIKit
import Flutter
import FirebaseCore. //import this
import FirebaseDatabase // import this also

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
  
  // Configure with manual options. Note that projectID and apiKey, 
    though not
  // required by the initializer, are mandatory.
      
  //Now create the secondary app

      let secondaryOptions = FirebaseOptions(googleAppID: "<your id from second google jsoninfo.plist>",
                                             gcmSenderID: "<your id from second google jsoninfo.plist>")
      secondaryOptions.apiKey = "<your id from second google jsoninfo.plist>"
      secondaryOptions.projectID = "<your id from second google jsoninfo.plist>"

      // The other options are not mandatory, but may be required
      // for specific Firebase products.
      secondaryOptions.bundleID = "<your id from second google jsoninfo.plist>"
      //secondaryOptions.trackingID = "<your id from second google jsoninfo.plist>"
      secondaryOptions.clientID = "<your id from second google jsoninfo.plist>"
      secondaryOptions.databaseURL = "<your id from second google jsoninfo.plist>"
      secondaryOptions.storageBucket = "<your id from second google jsoninfo.plist>"
      secondaryOptions.androidClientID = "<your id from second google jsoninfo.plist>"
      //secondaryOptions.deepLinkURLScheme = "<your id from second google jsoninfo.plist>"
      secondaryOptions.appGroupID = nil
      
      // Configure an alternative SecondaryApp.
      FirebaseApp.configure(name: "SecondaryApp", options: secondaryOptions)

      // Retrieve a previous created named app.
       guard let secondary = FirebaseApp.app(name: "SecondaryApp")
        else { assert(false, "Could not retrieve SecondaryApp") }


      // Retrieve a Real Time Database client configured against a specific app.
      let secondaryDb = Database.database(app: secondary)
      
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }   
}

Note: All the options are not mandatory to fill only which is available in your googlejsoninfo.plist file

Reference: https://firebase.google.com/docs/projects/multiprojects

Upvotes: 0

Usama Ishfaq
Usama Ishfaq

Reputation: 111

As you mentioned normal way to create app, you can create Firebase app same way, using Firebase CLI and it will do work for you. all you need to do is create a second app too, but you need to specify name for second app. If you don't use name when an instance of Firebase is create by default Firebase project configured first is used. Or you can specify FirebaseOptions manually in main.dart as shown below.
Below is a code that will help you understand how you can use two separate Firebase projects in one app, or multiple projects as needed.


initMultipleApp() async {
  if (defaultTargetPlatform == TargetPlatform.android) {
    await Firebase.initializeApp(
        //Android app ID's from firebase console of project 1
        name: 'defaultApp',
        options: const FirebaseOptions(
          apiKey: 'youAPIKey',
          appId: 'youAppId',
          messagingSenderId: 'youMessagingSenderId',
          projectId: 'youProjectId',
          storageBucket: 'youStorageBucket',
        ));
  } else if (defaultTargetPlatform == TargetPlatform.iOS) {
    await Firebase.initializeApp(
        //iOS app ID's from firebase console of project 1
        name: 'defaultApp',
        options: const FirebaseOptions(
          apiKey: 'youAPIKey',
          appId: 'youAppId',
          messagingSenderId: 'youMessagingSenderId',
          projectId: 'youProjectId',
          storageBucket: 'youStorageBucket',
        ));
  }
  //initialize second app here
  if (defaultTargetPlatform == TargetPlatform.android) {
    await Firebase.initializeApp(
        //Android app ID's from firebase console of project 2
        name: 'secondApp',
        options: const FirebaseOptions(
          apiKey: 'youAPIKey',
          appId: 'youAppId',
          messagingSenderId: 'youMessagingSenderId',
          projectId: 'youProjectId',
          storageBucket: 'youStorageBucket',
        ));
  } else if (defaultTargetPlatform == TargetPlatform.iOS) {
    await Firebase.initializeApp(
        //iOS app ID's from firebase console of project 2
        name: 'secondApp',
        options: const FirebaseOptions(
          apiKey: 'youAPIKey',
          appId: 'youAppId',
          messagingSenderId: 'youMessagingSenderId',
          projectId: 'youProjectId',
          storageBucket: 'youStorageBucket',
        ));
  }
}

class Database {
  final FirebaseFirestore _firestore1 =
      FirebaseFirestore.instanceFor(app: Firebase.app('defualtApp'));  //use _firestore1 for data you want to fetch from 1st firebase project
  final FirebaseFirestore _firestore2 =
      FirebaseFirestore.instanceFor(app: Firebase.app('secondApp'));    //use _firestore2 for data you want to fetch from 2st firebase project
  //use _firestore1 and _firestore2 to access the database as needed
}

In the code above you will be assigning ID's manually that this CLI based code is doing

await Firebase.initializeApp(
options: DefaultFirebaseOptions
    .currentPlatform, //auto choose from firebase_options file present in lib folder
  );

What this DefaultFirebaseOptions does is create Firebase app based on platform during execution. This is handled in lib/firebase_options.dart file if you initialized Firebase using CLI. And if you manually added google-services.json file in Android folder and GoogleServices-info.plist file in iOS. They will also include similar ID's.

Upvotes: 6

Zahra
Zahra

Reputation: 426

For connecting your Flutter app to a Firebase project, you can use:

flutterfire configure

Which, by default will add lib/firebase_option.dart file

If, for example, you want to integrate two separate firebase projects, one for dev and one for prod, you can make two directories:

lib/firebase/dev
lib/firebase/prod

Then run these separately:

flutterfire configure -p firebase-project-id-dev , -o lib/firebase/dev/firebase_options.dart

flutterfire configure -p firebase-project-id-prod , -o lib/firebase/prod/firebase_options.dart

Answer the upcoming questions for each command and ensure you see Firebase configuration file lib/firebase/prod/firebase_options.dart generated successfully to ensure your firebase_option has been created in the correct directory.

You can find your firebase-project-id in the firebase console: project overview > project setting > General > Project ID

BTW, here is some useful info about flutterfire configure [arguments]:

Usage: flutterfire configure [arguments]
-h, --help                                  Print this usage information.
-p, --project=<aliasOrProjectId>            The Firebase project to use for this command.
-e, --account=<email>                       The Google account to use for authorization.
-o, --out=<filePath>                        The output file path of the Dart file that will be generated with your Firebase configuration options.
                                            (defaults to "lib/firebase_options.dart")
-i, --ios-bundle-id=<bundleIdentifier>      The bundle identifier of your iOS app, e.g. "com.example.app". If no identifier is provided then an attempt will be made to automatically detect it from your "ios" folder (if it exists).
-m, --macos-bundle-id=<bundleIdentifier>    The bundle identifier of your macOS app, e.g. "com.example.app". If no identifier is provided then an attempt will be made to automatically detect it from your "macos" folder (if it
                                            exists).
-a, --android-app-id=<applicationId>        The application id of your Android app, e.g. "com.example.app". If no identifier is provided, then an attempt will be made to automatically detect it from your "android" folder (if it
                                            exists).

Run "flutterfire help" to see global options.

This article explains the multi-environment in detail for flutter and firebase.

Upvotes: 12

Renik Shiroya
Renik Shiroya

Reputation: 369

You can try this by adding flavors in flutter

https://codewithandrea.com/articles/flutter-flavors-for-firebase-apps/

Upvotes: 1

Related Questions