Flutter Firebase Cloud 功能:无法读取数据,因为格式不正确

Lab*_*Lab 3 firebase flutter google-cloud-functions

我尝试使用 Flutter 项目中的 cloud_functions 插件调用我的云函数,代码如下:

\n
final HttpsCallable callable = new CloudFunctions(region: "europe-west3")\n        .getHttpsCallable(functionName: 'helloWorld');\n\ndynamic resp = await callable.call(<String, dynamic>{'id': id, 'chatId': chat.chatId});\n
Run Code Online (Sandbox Code Playgroud)\n

并得到以下错误:

\n
ERROR: PlatformException(3840, The data couldn\xe2\x80\x99t be read because it isn\xe2\x80\x99t in the correct format., null)\n
Run Code Online (Sandbox Code Playgroud)\n

通过我的研究,我发现当您忘记将区域放在服务器和客户端上时,可能会出现问题,但错误仍然存​​在。

\n

我还尝试传递成功的 http 请求:

\n
var parameters = {'id': id, 'chatId': chat.chatId};\nvar url = "https://europe-west3-{MY_DOMAIN}.cloudfunctions.net/helloWorld";\nawait http.post(url, body: parameters).then((res) {...}\n
Run Code Online (Sandbox Code Playgroud)\n

所以我认为问题出在插件上,我可能忘记了一些东西。有任何想法吗 ?

\n

云功能(测试):

\n
exports.helloWorld = functions\n  .region('europe-west3')\n  .https.onRequest((request, response) => {\n    try {\n      response.send('Hello from Firebase!');\n    } catch (e) {\n      console.log(e);\n      throw new functions.https.HttpsError('calc-error', e);\n    }\n  });\n\n
Run Code Online (Sandbox Code Playgroud)\n

Eri*_*gel 5

当您在 Flutter 应用程序上使用 a 时callable,请尝试将您的函数转换为 useonCall而不是onRequest

Firebase 功能使用onCall

export const helloWorld = functions.https.onCall((data, context) => {
  functions.logger.info("data:", data);
  return {
    message: "bye!"
  };
});
Run Code Online (Sandbox Code Playgroud)

颤动应用程序:

模拟器设置:

  // after: Firebase.initializeApp()
  FirebaseFunctions.instance.useFunctionsEmulator(origin: 'http://localhost:5001');

Run Code Online (Sandbox Code Playgroud)

调用函数:

  FirebaseFunctions functions = FirebaseFunctions.instance;

  HttpsCallable callable = functions
      .httpsCallable('helloWorld');
  final results = await callable.call({
    'name': 'Erick M. Sprengel',
    'email': 'erick@mail.com'
  });
Run Code Online (Sandbox Code Playgroud)

请注意与onCall之间的区别onRequest。很容易转换,但我认为最好检查这个问题:Firebase Cloud Functions: Difference Between onRequest and onCall

额外提示:

  • 我正在使用模拟器,并且没有设置区域。
  • 请记住在每次更改后重新构建您的函数。我在用着npm run build -- --watch