简体   繁体   English

如何在模拟器演示项目中使用 FlutterFire?

[英]How do I use FlutterFire with a emulator demo project?

I am using the firebase emulator with demo project , without any actual firebase project resource created.我正在使用带有演示项目的 firebase 模拟器,没有创建任何实际的 firebase 项目资源。 I am doing so with the following command...我正在使用以下命令执行此操作...

firebase emulators:start --project demo-test --only firestore

This successfully starts a Firebase emulator instanceat localhost:8080.这成功地在 localhost:8080 启动了一个 Firebase 模拟器实例。

Then I am connecting to the firebase in my flutter app as follows...然后我在我的颤振应用程序中连接到firebase,如下所示......

await Firebase.initializeApp();
FirebaseFirestore.instance.settings = const Settings(
  host: 'localhost:8080',
  sslEnabled: false,
  persistenceEnabled: false,
);

When initializeApp is run, I get the following error...运行 initializeApp 时,出现以下错误...

E/flutter ( 7724): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.
E/flutter ( 7724):
E/flutter ( 7724): Usually this means you've attempted to use a Firebase service before calling `Firebase.initializeApp`.
E/flutter ( 7724):
E/flutter ( 7724): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization
E/flutter ( 7724):
E/flutter ( 7724): #0      MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:113
E/flutter ( 7724): <asynchronous suspension>
E/flutter ( 7724): #1      Firebase.initializeApp
package:firebase_core/src/firebase.dart:40
E/flutter ( 7724): <asynchronous suspension>
E/flutter ( 7724): #2      _MyHomePageState._asyncInit
package:mobile_app/main.dart:53
E/flutter ( 7724): <asynchronous suspension>
E/flutter ( 7724):

My current app has AppConfig class that extends InheritedWidget that keeps instance available when in use.我当前的应用程序具有扩展InheritedWidget的 AppConfig 类,该类在使用时保持实例可用。

You can try with你可以试试

class AppConfig extends InheritedWidget {

    static AppConfig? of(BuildContext context) {
        initializeFirebase();
        return context.dependOnInheritedWidgetOfExactType<AppConfig>();
      }
    
    static Future<void> initializeFirebase() async {
        try {
          await Firebase.initializeApp();
        } catch (e) {}
      }
}

You need to initialise the AppConfig() in main()您需要在 main() 中初始化 AppConfig()

  1. Try to change localhost to your machine ip, in both firebase command line and your app.尝试在 firebase 命令行和您的应用程序中将localhost更改为您的机器 ip。 Some simulators, such as ios simulator, cannot understand localhost.有些模拟器,比如ios模拟器,无法理解localhost。
  2. Please paste a fully reproducible sample, instead of just part of the lines.请粘贴完全可重现的样本,而不是仅粘贴部分行。
  3. Try to await Firebase.initializeApp();尝试await Firebase.initializeApp(); inside main function, not initStatemain函数内部,而不是initState
  4. Firstly check at port 8080 manually and see whether the firebase server really works首先手动检查8080端口,看看firebase服务器是否真的工作

Technically, the problem is not with the emulator.从技术上讲,问题不在于模拟器。 There are two problems with the code here.这里的代码有两个问题。

Problem 1: Incorrect connection to the emulator问题一:模拟器连接不正确

Providing 'localhost:8080' to the host argument for Firestore Settings is not asking FlutterFire to use the emulator.为 Firestore Settingshost参数提供 'localhost:8080'并不是要求FlutterFire 使用模拟器。 The right way to use the emulator for Firestore is使用 Firestore 模拟器的正确方法是

FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);

You could wrap that call in an if statement checked against !kReleaseMode so that you won't need to comment it out when you want to build the application.您可以将该调用包装在一个针对!kReleaseMode进行检查的 if 语句中,这样您在构建应用程序时就不需要将其注释掉。 Remember to import flutter/foundation.dart .记得导入flutter/foundation.dart

Problem 2: No FirebaseOptions provided问题 2:没有提供FirebaseOptions

The following error:以下错误:

E/flutter ( 7724): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized. E/flutter(7724):[错误:flutter/lib/ui/ui_dart_state.cc(198)] 未处理的异常:[core/not-initialized] Firebase 尚未正确初始化。

is caused from your Firebase.initializeApp() statement.是由您的Firebase.initializeApp()语句引起的。

Firebase.initializeApp() takes an optional named options argument whose value is a type of FirebaseOptions (with parameters like apiKey , appId , projectId , ...), and you are not providing it. Firebase.initializeApp()接受一个可选的命名options参数,其值为FirebaseOptions类型(带有apiKeyappIdprojectId等参数),而您没有提供它。

The FirebaseOptions for each platform (android, ios, and web) are available in the Firebase console of a given project.每个平台(android、ios 和 web)的FirebaseOptions在给定项目的 Firebase 控制台中可用。 Firebase can't be initialized for any client without its own config or FirebaseOptions .没有自己的配置或 FirebaseOptions 的任何客户端都无法初始化FirebaseOptions

To setup Firebase in a Flutter project, you need to run the flutterfire configure command in that flutter project folder.要在 Flutter 项目中设置 Firebase,您需要在该 Flutter 项目文件夹中运行flutterfire configure命令。 The command will ask you to choose a project from the Firebase console.该命令将要求您从 Firebase 控制台中选择一个项目。 The command will then fetch configs or FirebaseOptions for each platform and make them available through some switch statements for the currentPlatform in a firebase_options.dart file.然后,该命令将为每个平台获取配置或FirebaseOptions ,并通过firebase_options.dart文件中的 currentPlatform 的一些 switch 语句使它们可用。

You then have to import this file in main.dart and call initializeApp with the option for the given platform as according to the docs :然后,您必须在main.dart中导入此文件,并根据文档使用给定平台的选项调用initializeApp

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

Note that the command can also create apps for you in the Firebase project, if you haven't yet created them.请注意,如果您尚未创建应用,该命令还可以在 Firebase 项目中为您创建应用。

Let's dive deeper让我们更深入地了解

The options parameter is optional, but it is technically required. options参数是可选的,但在技术上是必需的。 If you look at the source code for Firebase.initializeApp() , you will see that under the hood, it invokes MethodChannel calls for the underlying platform (android, ios, or web) on which Flutter is running.如果您查看Firebase.initializeApp()的源代码,您会发现它在底层调用了运行 Flutter 的底层平台(android、ios 或 web)的 MethodChannel 调用。 So, if this MethodChannel is called without options , some coreNotInitialized() is thrown.因此,如果在没有options的情况下调用此 MethodChannel,则会抛出一些coreNotInitialized()

The following is from here以下是从这里

// If there is no native default app and the user didn't provide options to
// create one, throw.
if (defaultApp == null && _options == null) {
  throw coreNotInitialized();
}

This snippet is from initializeApp method in method_channel_firebase.dart file.此片段来自method_channel_firebase.dart文件中的initializeApp方法。

There is a conditional block two steps before this one that checks if the current platform is android and if there is a default firebase app available from native android resources.在这一步之前有一个条件块,它检查当前平台是否为 android 以及是否有可从原生 android 资源获得的默认 firebase 应用程序。 This probably explains why options (as well as name ) are optional at the high-level exposed package.这可能解释了为什么options (以及name )在高级暴露包中是可选的。

Thinking deeper, it makes sense that you must provide FirebaseOptions to Firebase.initializeApp() .深入思考,您必须Firebase.initializeApp()提供FirebaseOptions是有道理的。 If you were coding for a specific platform and you were to integrate Firebase or use any of its services, you have to provide those options in one way or the other.如果您正在为特定平台进行编码,并且要集成 Firebase 或使用其任何服务,则必须以一种或另一种方式提供这些选项。 In fact, with Flutter, in the past, when the flutterfire command was not yet available, setting up Firebase for Flutter had to be done manually for each platform (in its own folder).事实上,对于 Flutter,在过去,当flutterfire命令尚不可用时,必须为每个平台手动设置 Firebase for Flutter(在其自己的文件夹中)。

Now that Dart-only Firebase setup is available in the main.dart file directly, it still requires that the FirebaseOptions for each platform is provided.现在可以直接在main.dart文件中使用 Dart-only Firebase 设置,它仍然需要为每个平台提供FirebaseOptions And that is what the flutterfire CLI does during the setup process.这就是flutterfire CLI 在设置过程中所做的事情。 It fetches the configs for each platform and imports them.它获取每个平台的配置并导入它们。 In fact, the docs also specify that you should run flutterfire configure after adding a specific Firebase product plugin .事实上, 文档还指定您应该在添加特定的 Firebase 产品插件后运行flutterfire configure

Solution解决方案

So it is clear that to work with any client, you must properly connect a Firebase project from the Firebase console, because the client needs the project's config or FirebaseOptions .因此很明显,要使用任何客户端,您必须从 Firebase 控制台正确连接 Firebase 项目,因为客户端需要项目的配置或FirebaseOptions

Since you want to work with demo stuff, use the "explore a demo project" feature in the firebase console.由于您想使用演示内容,请使用 firebase 控制台中的“探索演示项目”功能。 This creates a valid temporary Firebase project.这将创建一个有效的临时 Firebase 项目。

Then when you run the flutterfire configure command, you select this demo project and use it instead.然后当你运行flutterfire configure命令时,你选择这个演示项目并使用它。

Furthermore, the Firebase emulators don't use production resources.此外,Firebase 模拟器不使用生产资源。 So as you start the emulators with --only firestore , firestore calls will all be done locally.因此,当您使用--only firestore启动模拟器时,firestore 调用将全部在本地完成。 That said, if you configure FlutterFire with a valid Firebase project, and you use the firestore emulator, you have nothing to fear with regards to interacting with production APIs.也就是说,如果您使用有效的 Firebase 项目配置 FlutterFire,并使用 firestore 模拟器,那么您无需担心与生产 API 交互。

Note that you can use the console demo project with whatever emulator for Firebase service.请注意,您可以将控制台演示项目与 Firebase 服务的任何模拟器一起使用。 But remember that these services like firestore for example, are not enabled in the demo project in itself, so if you try to test code against production firestore for the demo project, it won't work.但请记住,这些服务(例如 firestore)本身并未在演示项目中启用,因此如果您尝试针对演示项目的生产 firestore 测试代码,它将无法正常工作。

Also, the demo project in the Firebase console has to be in view while you work with it.此外,您必须在使用 Firebase 控制台时查看演示项目。 There is an "Exit Project" button up top.顶部有一个“退出项目”按钮。 Once you exist, you've lost the demo project and may have to click on "explore a demo project" again from the home screen to access another demo project一旦存在,您就丢失了演示项目,可能必须再次从主屏幕单击“探索演示项目”才能访问另一个演示项目

Recap回顾

So ensure your main method looks like this:因此,请确保您的主要方法如下所示:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
  runApp(const MyApp());
}

And even if you are using a demo emulator, it should now work as expected.即使您使用的是演示模拟器,它现在也应该可以按预期工作。

inside main() you can write like this for initilize :在 main() 里面,你可以这样写 initilize :

void main() async { 
   WidgetsFlutterBinding.ensureInitialized(); 
   await Firebase.initializeApp();
}

and other thing you have to write :和其他你必须写的东西:

inside android/app/build.gradle file at the bottom在底部的 android/app/build.gradle 文件中

apply plugin: 'com.google.gms.google-services'

and try this.试试这个。

[EDIT] [编辑]

you can check this github post as issue is accepted from flutter as well : https://github.com/firebase/flutterfire/issues/8898您可以查看此 github 帖子,因为问题也已从 Flutter 中接受: https ://github.com/firebase/flutterfire/issues/8898

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用模拟器在 Android Studio 中加载 React Native 项目? - How do I load React Native Project in Android Studio with an emulator? 如何为我的React Native项目合并一个Android模拟器? - How do I incorporate an Android emulator for my React Native project? 如何将ARC Welder用作Android模拟器 - How do I use ARC Welder as an Android emulator 如何使用这个 Android 模拟器错误补丁? - How do I use this Android Emulator Bug Patch? 如何通过网络演示我的Android应用程序 - How do I demo my android application over the web 使用Robotium作为Android Project的简介/演示文稿 - Use Robotium as intro/demo presentation for Android Project 如何指定Android模拟器应在我的开发计算机上使用哪个网络接口? - How do I specify which network interface the Android emulator should use on my development machine? 当 Windows 已经在使用 android 仿真器时,如何让它使用端口 1900? - How do I get the android emulator to use port 1900 when it's already being used by Windows? 如何使用 kotlin 代码修改 android 仿真器中出现的文本? - How do I use kotlin codes to modify text appears in android emulator? 如何在 Android Studio 中激活模拟器? - How do I activate the emulator in Android Studio?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM