首页 > 解决方案 > Flutter Firebase Cloud 功能无法调用

问题描述

当我尝试从 Flutter 调用可调用函数时,我在使用 Firebase Cloud Functions 时遇到错误。

flutter: caught generic exception
flutter: PlatformException(functionsError, Firebase function failed with exception., {message: NOT FOUND, code: NOT_FOUND})

以下是我尝试使用 cloud_functions 调用云函数的方法:^0.4.2+3

import 'package:cloud_functions/cloud_functions.dart';
      _check(String id) async {
        HttpsCallable callable = CloudFunctions.instance
            .getHttpsCallable(functionName: 'checkUserFavorites');
        try {
          final HttpsCallableResult result = await callable.call(
            <String, dynamic>{
              'id': id,
            },
          );
          print(result.data);
        } on CloudFunctionsException catch (e) {
          print('caught firebase functions exception');
          print(e.code);
          print(e.message);
          print(e.details);
        } catch (e) {
          print('caught generic exception');
          print(e);
        }
      }

标签: fluttergoogle-cloud-functions

解决方案


我遇到过类似的问题,经过几天的调试和实验,我在研究了Flutter 的 Cloud Functions Plugin源代码后才找到了解决方案。

当您部署 Firebase Cloud 功能时,您可以选择任何偏好区域(越靠近您的应用程序越好)。例如

// using DigitalOcean spaces
exports.generateCloudImageUrl = functions
    .region('europe-west3')
    .https.onCall((reqData, context) => {
...
}

当你想从 Flutter 应用程序调用这个函数时,你必须指定区域,否则一切都去us-central1哪个是默认的。请参阅有关如何使用部署在特定区域中的功能的示例代码

final HttpsCallable generateCloudImageUrl = new CloudFunctions(region: "europe-west3")
      .getHttpsCallable(functionName: 'generateCloudImageUrl');

// NB! if you initialize with 'CloudFunctions.instance' then this uses 'us-central1' as default region! 

请参阅cloud_function的 init 源代码。

更新,截至最近的版本,你可以初始化如下;

FirebaseFunctions.instanceFor(region: "europe-west3").httpsCallable(
            "generateCloudImageUrl",
            options:
                HttpsCallableOptions(timeout: const Duration(seconds: 30)));

推荐阅读