【问题标题】:Flutter + firebase: Configure app to use local firebase emulatorFlutter + firebase:配置应用程序以使用本地 firebase 模拟器
【发布时间】:2020-02-29 19:03:02
【问题描述】:

我已通过this 链接将firebase 配置为在本地运行以使用模拟器进行调试。

现在我希望能够运行连接到本地主机的应用程序以调试触发器。有没有办法通过将我的颤振应用程序配置为使用本地主机来实现这一点?

我的模拟器运行如下:

【问题讨论】:

  • 请不要显示文字图片。最好将文本直接复制到问题中,以便于阅读和搜索。
  • 如果您只需要部分配置您的应用程序。例如,只有 firestore 或只有功能。您可以在这里使用代码:tianhaoz.com/eng/server/firebase/…

标签: firebase flutter google-cloud-functions


【解决方案1】:

我最新的flutter fire设置

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

  const bool USE_EMULATOR = true;

  if (USE_EMULATOR) {
    // [Firestore | localhost:8080]
    FirebaseFirestore.instance.settings = const Settings(
      host: 'localhost:8080',
      sslEnabled: false,
      persistenceEnabled: false,
    );
    
    // [Authentication | localhost:9099]
    await FirebaseAuth.instance.useEmulator('http://localhost:9099');

    // [Storage | localhost:9199]
    await FirebaseStorage.instance.useEmulator(
      host: 'localhost',
      port: 9199,
    );
  }
}

确保您的主机和端口与firebase emulators:start 匹配

注意:在main.dart 现在您可以随时提供'localhost'

await FirebaseAuth.instance.useEmulator('http://localhost:9099');

因为如果它在 android 上运行,它会自动更改为“10.0.2.2”

长话短说!

如需最新指南,请关注https://firebase.flutter.dev/docs/firestore/usage#emulator-usage

老但是,黄金。详细配置。(过时)

步骤 1 [在 main.dart 中设置 firestore]

Future<void> main() async {
  
    WidgetsFlutterBinding.ensureInitialized(); <--- Important!
      
    await Firestore.instance.settings(
            host: '192.168.1.38:5002', <--- Make sure to put your local ip 
            sslEnabled: false);             it will not work if you use 'localhost:5002'
                                            Google it "how to find my local ip"
       
}

第 1 步 [在 main.dart 中的 flutter 中设置 firestore] 用于更新版本的 firebase

Future<void> main() async {
  
    WidgetsFlutterBinding.ensureInitialized(); <--- Important!
   
    String host = Platform.isAndroid ? '10.0.2.2:5002' : 'localhost:5002';
    await FirebaseFirestore.instance.settings = Settings(
         host: host,
         sslEnabled: false,
    );  
       
}

第 2 步 [初始化 firebase 项目]

firebase init

第 3 步 [配置 firestore 模拟器,例如 firebase.json]

"emulators": {
    "ui": {
      "enabled": true,
      "host": "localhost",
      "port": 4000
    },
    "functions": {
      "port": 5001
    },
    "firestore": {
      "host": "0.0.0.0", <------ Make sure to set it "0.0.0.0"
      "port": 5002
    },
}

第 4 步 [运行模拟器和 Flutter 应用]

firebase emulators:start
flutter run

在 iOS 模拟器和 Android 模拟器上都工作过

P.S:尝试重新启动 Firestore 模拟器或/和 Flutter 应用

完成!

BONUS [将导出数据导入到 Firestore 模拟器]

当您停止 firestore 模拟器时,firestore 中的所有数据都将消失。 所以如果你想从哪里继续,也许在停止模拟器之前 你剩下的可以像这样导出firestore模拟器数据

firebase emulators:export ../data(../data 可以是你想要的任何路径?)

加载导出的数据

firebase emulators:start --import ../data

您可以为不同的情况保存 Firestore 模拟器的不同状态,例如

firebase emulators:start --import ../initialData 
firebase emulators:start --import ../otherStateData

❤️ 自己的注意事项将 dart 用于 firebase 功能 ❤️

如果您想将 dart 用于 firebase 功能,可以关注此https://github.com/pulyaevskiy/firebase-functions-interop

我为自己发现了一件好事,可以检测您的功能是在 emulator 还是 production 中运行,您可以阅读更多 here

长话短说

functions/index.js

export const prepopulateFirestoreEmulator = functions.https.onRequest(
  (request, response) => {
    if (process.env.FUNCTIONS_EMULATOR && process.env.FIRESTORE_EMULATOR_HOST) {
      // TODO: prepopulate firestore emulator from 'yourproject/src/sample_data.json
      response.send('Prepopulated firestore with sample_data.json!');
    } else {
      response.send(
        "Do not populate production firestore with sample_data.json"
      );
    }
  }
);

函数/index.dart

import 'package:firebase_functions_interop/firebase_functions_interop.dart';
import 'package:node_interop/node.dart';
import 'package:node_interop/util.dart';

void devPrepopulateCollections(ExpressHttpRequest request) {
  var env =
      new Map<String, String>.from(dartify(process.env)); // <-- important part

  if (env.containsKey('FUNCTIONS_EMULATOR') &&
      env.containsKey('FIRESTORE_EMULATOR_HOST')) {
    // TODO: prepopulate firestore emulator from 'yourproject/src/sample_data.json
    request.response
      ..write("Prepopulated firestore with sample_data.json!")
      ..close();
  } else {
    request.response
      ..write("Do not populate production firestore with sample_data.json")
      ..close();
  }
}

【讨论】:

  • 感谢您的指导!这甚至适用于我连接的 Android 设备。
  • 现在flutter有官方说明为flutter设置firebase模拟器firebase.flutter.dev/docs/firestore/usage#emulator-usage
  • 你能更新一下如何连接到实时数据库模拟器吗?我不知道需要什么魔法咒语……
  • 官方说明适用于使用 Android 或 iOS 模拟器。但是在物理设备上测试,需要Firestore主机“0.0.0.0”+本地IP组合
  • @SultanmyrzaKasymbekov 感谢您的回答!您知道将 Firebase Emulator 与 FirebaseAuth 和 Flutter 结合使用的相同解决方案吗?
【解决方案2】:

在仔细阅读文档 here 后,我通过在 firestore 实例上配置主机设置使其工作:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:tracker/screens/screens.dart';

void main() async {

  // This will set the app to communicate with localhost
  await Firestore.instance.settings(host: "10.0.2.2:8080", sslEnabled: false);

  runApp(AppSetupScreen());
}

注意:这仅适用于模拟器,不适用于物理设备。

【讨论】:

  • 在iOS模拟器中能用吗?我试过使用它,请求仍然去火力基地而不是火力基地模拟器:/
  • 抱歉,我没有在 iOS 模拟器中尝试过:/,但它应该可以通过将“localhost:8080”作为文档中指定的主机来工作。
  • @kashlo 是的,如果您关注此stackoverflow.com/a/62586957/6133329,它适用于 iOS/Android
【解决方案3】:

一个插件:

让 Firebase 模拟器与物理设备一起工作

适用于 iOS 和 Android 设备

1。云功能设置:

firebase.json

{
  // ...other configs
  "emulators": {
    "functions": {
      "port": 5001,
      "host": "0.0.0.0" // must have
    },
    "firestore": {
      "port": 8080,
      "host": "0.0.0.0" // must have
    },
  }
}

2。您的 Flutter 应用设置:

您用于云功能和 Firestore 的 IP 地址应相同

// The FirebaseFunctions config
// ! You need to replace the placeholder with your IP address below:
FirebaseFunctions.instance.useFunctionsEmulator(origin: 'http://<YOUR_IP_ADDRESS>:5001');

// The Firestore config
// ! You need to replace the placeholder with your IP address below:
FirebaseFirestore.instance.settings = Settings(
  host: '<YOUR_IP_ADDRESS>:8080',
  sslEnabled: false,
  persistenceEnabled: false,
);

【讨论】:

    【解决方案4】:

    对于cloud_firestore: ^0.14.1+2,而不是使用FirebaseFirestore.instance.settings 使用这个-

    FirebaseFunctions.instance.useFunctionsEmulator(
        origin: "http://localhost:5001",
      );
    

    如果设备是 android,它会在内部处理设置 10.0.2.2

    您的主块应如下所示

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseFunctions.instance.useFunctionsEmulator(
        origin: "http://localhost:5001",
      );
      runApp(MyApp());
    }
    

    【讨论】:

    • 我认为您正在混合功能和 Firestore。
    【解决方案5】:

    看起来我已将 ios 连接到 localhost:8080,但 db 运行速度非常慢,而且我也没有注意到文件中的任何日志。 @UsmanZaheer,你能告诉我它是什么时候写日志的,它工作得很快吗?

    步骤:

    • firebase 初始化

    • 将ini创建的链接添加到functions中的package.json;

      “火库”:{ “规则”:“firestore.rules”, “索引”:“firestore.indexes.json” },

    • firebase 模拟器:开始

    在 main() 中写入

    await Firestore.instance.settings(
          host: 'http://localhost:8080',
          sslEnabled: false,
          persistenceEnabled: false,
          timestampsInSnapshotsEnabled: true
      ).catchError((e) => print(e));
    

    【讨论】:

    • 模拟器仅用于调试目的,我用它来调试我的云功能。当您创建一个 auth 用户时,它会保存到 firestore,因为目前没有 auth 模拟器,至于其他数据,我真的不能说它存储数据的位置(可能在内存中)。模拟器只是在控制台中显示该函数已被命中以及成功或错误。
    【解决方案6】:

    您的main.dart 应如下所示:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firestore.instance
        .settings(
           host: 'http://localhost:8080',
           sslEnabled: false,
           persistenceEnabled: false,
         )
        .catchError((e) => print(e));
      // 
      // ...
      //
      runApp(App(...));
    }
    

    在您的firebase.json 文件中

      "emulators": {
        "firestore": {
              "host": "localhost",
              "port": 8080
        },
        ...
      }
    

    您还应该在终端中设置以下内容:

    export FIRESTORE_EMULATOR_HOST=localhost:8080
    

    然后运行

    firebase emulators:start
    

    【讨论】:

      【解决方案7】:

      Flutter Web 调整

      除了correct answer by @Sultanmyrza

      Platform 需要 dart:io/dart:html 是互斥的,所以要检查我使用的平台 kIsWeb

      FirebaseFirestore __firestore;
      FirebaseFirestore get _firestore {
        if (__firestore != null) {
          return __firestore;
        }
        debugPrint('isFirebaseEmulator: $isFirebaseEmulator');
        __firestore = FirebaseFirestore.instance;
        if (isFirebaseEmulator) {
          __firestore.settings = const Settings(
            host: kIsWeb ? 'localhost:8080' : '10.0.2.2:8080',
            sslEnabled: false,
          );
        }
        return __firestore;
      }
      

      【讨论】:

        【解决方案8】:

        最新更新:要将 Flutter 应用连接到您本地的 Firebase 模拟器套件,请按照 this 官方说明进行配置。

        【讨论】:

          猜你喜欢
          • 2021-11-19
          • 2020-11-09
          • 1970-01-01
          • 1970-01-01
          • 2020-12-02
          • 1970-01-01
          • 2020-11-09
          • 2021-09-12
          • 2019-07-08
          相关资源
          最近更新 更多