【问题标题】:How can I invoke and use Google Cloud Functions in a Flutter app?如何在 Flutter 应用中调用和使用 Google Cloud Functions?
【发布时间】:2020-09-19 07:24:26
【问题描述】:

我创建了一个 url scraper 函数,在 Google Cloud 上运行和测试,但我真的对如何调用它一无所知。我尝试了两种方法,一种使用 cloud_functions 包,另一种使用标准 HTTPS 获取。我尝试在网上查找,但没有一个解决方案/指南涉及具有来自 Flutter 应用程序的输入和返回到应用程序的输出的功能。

这是函数的结构(工作正常)。我在 Google Cloud Platform 中将此函数命名为 Parse。

<PYTHON PACKAGE IMPORTS>

def Parser(url):
    <URL PARSE FUNCTIONS>
    return source, datetime, imageurl, keyword

def invoke_parse(request):
    request_json = request.get_json(silent=True)
    file = Parser(request_json['url'])
    return jsonify({
        "source": file[0],
        "datetime": file[1],
        "imageurl": file[2],
        "keyword": file[3],
    })

我尝试的第一种方法是使用 HTTP CALL 来获取函数。但这不起作用,即使没有错误 - 我怀疑它只是没有返回任何内容。

parser(String url) async{          // Here I honestly don't know where to use the url input within the function
    var uri = Uri.parse(<Function URL String>);
    HttpClient client;
    try {
      var request = await client.getUrl(uri);
      var response = await request.close();
      if (response.statusCode == HttpStatus.ok) {
        var json = await response.transform(utf8.decoder).join();
        Map data = jsonDecode(json) as Map;
        source = data['source'];            // These are the variables used in the main Flutter app
        postedAt = data['datetime'];
        _imageUrl = data['image'];
        keyword = data['keyword'];
      } else {
         print('Error running parse:\nHttp status ${response.statusCode}');
      }
    } catch (exception) {
      print('Failed invoking the parse function.');
    }
}

那没用,所以我想我可以替代地使用 cloud_functions 包,如下所示(代替前面的):

  parser(String url) async {
    var functionUrl = <FUNCTION URL>;
    HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(functionName: 'Parse')
      ..timeout = const Duration(seconds: 30);
    try {
      final HttpsCallableResult result = await callable.call(
          <String, dynamic>{
            'url': url,
          }
      );
      setState(() {
        source = result.data['source'];       //THESE ARE VARIABLES USED IN THE FLUTTER APP
        postedAt = result.data['datetime'];
        _imageUrl = result.data['image'];
        keyword = result.data['keyword'];
      });
    }
      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);
    }
    }

在后一种情况下,代码运行没有错误,但不起作用。我的颤振日志指出以下错误:

I/flutter ( 2821): caught generic exception
I/flutter ( 2821): PlatformException(functionsError, Cloud function failed with exception., {code: NOT_FOUND, details: null, message: NOT_FOUND})

我假设这也是无法读取函数的错误。

任何关于我应该如何处理我的函数的帮助将不胜感激。抱歉,如果某些东西是一个非常明显的解决方案,但我对 HTTP 请求和云平台不太熟悉。

感谢和欢呼。

【问题讨论】:

  • 您在第一个 sn-p 中定义的是 HTTP(S) 函数,而不是 Firebase 特定的可调用函数。因此,您当前尝试将其作为可调用函数调用的方法是行不通的。我看到您说“我尝试的第一种方法是使用 HTTP CALL 来获取函数”,但我们需要查看该代码以及任何相关的错误/日志消息才能提供帮助和调试。
  • 那个代码就是我所说的调用函数的意思。我怀疑我使用的术语可能非常不正确。老实说,我什至无法理解函数调用在那个 sn-p 中发生的位置。比如参数是如何传递的?
  • 啊,我现在看到你有两个客户端 sn-ps。您可能想使用HttpsCallable 删除它,因为它无论如何都无法工作(如上所述)。我也会删除所有关于 Callable 的提及以避免混淆,并让人们专注于最小的实际问题。
  • 实际上,它们是我尝试做同样事情的两种不同方法,而不是在相同的代码中。我已经编辑了我的问题以反映现在的变化,谢谢。
  • 我知道它们是两种不同的尝试,我试图解释为什么使用 HttpsCallable 的尝试不起作用。我也可以将其发布为答案,这将是您问题的有效答案。通过在评论中解释它,我试图帮助您将此问题集中在可以工作的唯一案例上,这样您就不必发布另一个问题。

标签: json flutter dart google-cloud-platform google-cloud-functions


【解决方案1】:

Node Js 后端函数

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.test = functions.https.onCall(async (data, context) => {
  functions.logger.info("Hello logs: ", {structuredData: true});
  functions.logger.info( data.token, {structuredData: true});
}

Flutter 前端

1- pubspec.yaml

cloud_functions: ^1.1.2

2 - 代码

HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('test');
    final HttpsCallableResult results = await callable.call<Map>( {
      'token': token,
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2021-12-26
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多