将两个不同的Firebase项目添加到Flutter项目

2skhul33  于 2023-04-22  发布在  Flutter
关注(0)|答案(4)|浏览(189)

我已经创建了一个flutter项目'example',我想添加到firebase项目'fire1'和'fire2'.在正常的方式添加firebase是通过添加google-services.jsonGoogleServices-Info.plist为IOS和Android.所以我怎么能添加两个firebase在一个flutter项目?

bnl4lu3b

bnl4lu3b1#

正如您提到的创建应用程序的正常方式,您可以使用Firebase CLI以相同的方式创建Firebase应用程序,它将为您工作。您需要做的就是创建第二个应用程序,但您需要为第二个应用程序指定名称。如果您在默认情况下创建Firebase示例时不使用名称,则使用首先配置的Firebase项目。或者您可以在main.dart中手动指定FirebaseOptions,如下所示。
下面的代码将帮助您了解如何在一个应用中使用两个单独的Firebase项目,或根据需要使用多个项目。

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
}

在上面的代码中,您将手动分配此基于CLI的代码正在执行的ID

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

这个DefaultFirebaseOptions的作用是在执行过程中根据平台创建Firebase应用。如果您使用CLI初始化Firebase,则在lib/firebase_options.dart文件中处理。如果您手动添加Android文件夹中的google-services.json文件和iOS中的GoogleServices-info.plist文件,则也会包含类似的ID。

dfddblmv

dfddblmv2#

要将Flutter应用连接到Firebase项目,您可以用途:

flutterfire configure

默认情况下,将添加lib/firebase_option.dart文件
例如,如果你想集成两个独立的firebase项目,一个用于dev,另一个用于prod,你可以创建两个目录:

lib/firebase/dev
lib/firebase/prod

然后分别运行这些:

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

回答每个命令的后续问题,并确保您看到Firebase configuration file lib/firebase/prod/firebase_options.dart generated successfully,以确保您的firebase_option已在正确的目录中创建。
您可以在firebase控制台中找到您的firebase-project-id:project overview > project setting > General > Project ID
顺便说一句,这里有一些关于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详细解释了flutter和firebase的多环境。

yws3nbqq

yws3nbqq4#

在iOS中初始化两个Firebase应用:
步骤1:初始化Flutter主文件中的默认应用程序
第2步:在appdelegate文件中手动初始化第二个firebase应用,app目录中的第二个应用不需要googlejsoninfo.plist

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

注意:所有选项都不是必须填写的,仅在googlejsoninfo.plist文件中可用
参考:https://firebase.google.com/docs/projects/multiprojects

相关问题