向我的Flutter项目添加两个不同的Firebase项目



我创建了一个扑动项目'示例',我想添加到firebase项目'fire1'和'fire2'。添加firebase的正常方式是添加google-services.jsonGoogleServices-Info.plist(IOS和Android)。那么我如何在一个颤振项目中添加两个firebase ?

正如你提到的创建应用程序的正常方式,你可以用同样的方式创建Firebase应用程序,使用Firebase CLI,它会为你工作。你所需要做的就是创建第二个应用程序,但是你需要为第二个应用程序指定名称。如果你在创建Firebase实例时不使用名称,默认情况下会使用第一个配置的Firebase项目。或者你可以在main中手动指定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
}

在上面的代码中,您将手动分配ID,这是基于CLI的代码所做的

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

DefaultFirebaseOptions在执行过程中创建基于平台的Firebase应用程序。这在lib/firebase_options.dart中处理。如果您使用CLI初始化Firebase,则该文件。如果你手动添加了谷歌服务。Android文件夹中的googleeservices -info. json文件。iOS中的plist文件。它们还将包括类似的ID。

要将您的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配置[参数]的有用信息:

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.

本文详细说明了flutter和firebase的多环境。

您可以尝试在flutter中添加风味

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

在iOS中初始化两个Firebase应用程序:

步骤1:在Flutter主文件

中初始化默认应用程序步骤2:在app目录下的appdelegate文件nogooglejsoninfo.plist中手动初始化第二个firebase应用。

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

最新更新