从 Flutter 应用程序通过本地网络连接到 Firebase 功能模拟器

Connect to Firebase functions emulators over local network from a Flutter app

我正在尝试从我的测试 Android 设备连接到我的 Firebase 函数模拟器。

当我 运行 模拟器输出是:

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

在我的 Flutter 应用中,我执行以下连接:

FirebaseFunctions.instance.useFunctionsEmulator(origin: 'http://192.168.1.158:5001');

我已将 android:usesCleartextTraffic="true" 添加到我的 Android 清单和 network_security_config.xml and

我一直收到以下错误:

PlatformException(firebase_functions, com.google.firebase.functions.FirebaseFunctionsException: INTERNAL, {code: unavailable, message: com.google.firebase.functions.FirebaseFunctionsException: INTERNAL}

我做错了什么?

默认情况下,所有模拟器将仅侦听本地主机,而不侦听您的本地网络。

我尝试通过 运行 我在整个网络上的托管模拟器来复制您的问题,并且仅在本地主机上运行模拟器,如下面的屏幕截图所示。

const firebaseConfig = {...}
firebase.initializeApp(firebaseConfig);

firebase.functions().useEmulator("192.168.0.102", 5001);

var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: "messageText" }).then((result) => {
  // Read result of the Cloud Function.
  var sanitizedMessage = result.data.text;
}); 

我从文档中复制了示例函数并尝试调用该函数,结果如预期的那样:

如果您使用 firebase serve --only functions --host 0.0.0.0 提供函数,它应该使函数可用于您的网络。

或者,您可以在 firebase.json 中这样指定:

{
  "functions": {
    "predeploy": "npm --prefix \"$RESOURCE_DIR\" run build"
  },
  "emulators": {
    "functions": {
      "port": 5001,
      "host": "0.0.0.0"
    }
  }
}

然后您可以使用 firebase emulators:start.

简单地启动模拟器