Flutter云函数调用插件agconnect_cloudfunctions的使用

Flutter云函数调用插件agconnect_cloudfunctions的使用

目录

1. 引言

此插件使Huawei Cloud Functions SDK与Flutter平台之间能够通信。它提供了由Huawei Cloud Functions SDK提供的所有功能。

2. 安装指南

创建AppGallery Connect项目

在AppGallery Connect上创建一个项目,以便与华为的服务进行通信。步骤如下:

  1. 登录到AppGallery Connect,选择"My projects"。
  2. 从项目列表中选择您的项目或点击"Add Project"按钮创建一个新的项目。
  3. 转到"Project Setting" > “General information”,并点击"Add app"。 如果项目中已存在应用程序且您需要添加新应用程序,请展开页面顶部的应用程序选择区域并点击"Add app"。
  4. 在"Add app"页面上输入应用程序信息,然后点击"OK"。

申请云函数服务

云函数仍处于Beta状态。要使用云函数,请发送一封电子邮件至agconnect@huawei.com以申请服务。

邮件主题格式为:[Cloud Functions]-[公司名称]-[开发者账户ID]-[项目ID]。有关如何查询开发者账户ID和项目ID的详细信息,请参阅查询开发者账户ID和项目ID

华为运营人员将在1到3个工作日内回复。

启用云函数服务

  1. AppGallery Connect中,找到您的项目,并点击您想使用云函数的应用程序。
  2. 选择左侧菜单中的"Build"和"Cloud functions",然后点击"Enable Cloud Functions service"。

创建云函数

要创建云函数,请参考创建函数

集成Flutter云函数插件

Android应用开发
  1. 转到"Project Setting > General information"页面,在"App information"字段下,点击"agconnect-services.json"以下载配置文件。
  2. 将"agconnect-services.json"文件复制到项目的"example/android/app/"目录中。
  3. 打开项目的"example/android/build.gradle"文件。
    • 导航到"buildscript"部分,并为AppGallery Connect SDK配置Maven仓库地址和agconnect插件。
      buildscript {
        repositories {
            google()
            jcenter()
            maven { url 'https://developer.huawei.com/repo/' }
        }
      
        dependencies {
            /*
             * <其他依赖项>
             */
            classpath 'com.huawei.agconnect:agcp:1.7.1.300'
        }
      }
      
    • 转到"allprojects"并为AppGallery Connect SDK配置Maven仓库地址。
      allprojects {
        repositories {
            google()
            jcenter()
            maven { url 'https://developer.huawei.com/repo/' }
        }
      }
      
  4. 打开"example/android/app/build.gradle"文件。
    • 在其他"apply"条目之后添加一行apply plugin: 'com.huawei.agconnect'
      apply plugin: 'com.android.application'
      apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
      apply plugin: 'com.huawei.agconnect'
      
    • 在"defaultConfig > applicationId"中设置您的包名,并将"minSdkVersion"设置为17或更高版本。包名必须与"agconnect-services.json"文件中的"package_name"条目匹配。
      defaultConfig {
          applicationId "<package_name>"
          minSdkVersion 17
          /*
          * <其他配置>
          */
      }
      
iOS应用开发
  1. 转到"Project Setting > General information"页面,在"App information"字段下,点击"agconnect-services.plist"以下载配置文件。
  2. 将"agconnect-services.plist"文件复制到Xcode项目的根目录。

添加到库

  1. 在您的Flutter项目目录中,找到并打开"pubspec.yaml"文件,并在依赖项中添加"agconnect_cloudfunctions"库。更多详情请参阅使用软件包文档。
    • pub.dev下载包。
      dependencies:
        agconnect_cloudfunctions: {库版本}
      
  2. 运行以下命令更新包信息。
    [project_path]> flutter pub get
    
  3. 导入库以访问方法。
    import 'package:agconnect_cloudfunctions/agconnect_cloudfunctions.dart';
    
  4. 运行以下命令启动应用程序。
    [project_path]> flutter run
    

3. API参考

FunctionCallable

表示处理云函数的类。

公共构造函数摘要
构造函数 描述
FunctionCallable(String httpTriggerURI, [int timeout, AGCTimeUnit units]) 默认构造函数。
FunctionCallable.fromMap(Map<dynamic, dynamic> map) 从映射创建FunctionCallable对象。
FunctionCallable.fromJson(String source) 从JSON字符串创建FunctionCallable对象。
公共方法摘要
方法 返回类型 描述
Future<FunctionResult> call([dynamic functionParameters]) Future<FunctionResult> 此API用于配置并调用云函数。
公共构造函数
FunctionCallable(String httpTriggerURI, [int timeout, AGCTimeUnit units])

构造FunctionCallable对象的构造函数。

参数 类型 描述
httpTriggerURI String 要调用的云函数的HTTP触发器标识。有关查询HTTP触发器标识的详细信息,请参阅查询触发器标识
timeout int 函数的超时时间。对于Android,单位由timeUnit参数定义,默认单位为秒。对于iOS,时间单位为秒。此参数为可选。
units AGCTimeUnit 定义时间单位。此参数为可选。默认值为70。
公共方法
Future<FunctionResult> call([dynamic functionParameters]) async

配置并调用云函数。

参数 描述
functionParameters 云函数配置和参数。此参数为可选。
返回类型 描述
Future<FunctionResult> 函数执行后的返回值。
调用示例
FunctionCallable functionCallable = FunctionCallable(httpTrigger);
Person person1 = Person(1, 'Amy');
Person person2 = Person(2, 'Gunner');

List&lt;Map&lt;String, Object&gt;&gt; params = &lt;Map&lt;String, Object&gt;&gt;[
  person1.toMap(),
  person2.toMap()
];

FunctionResult functionResult = await functionCallable.call(params);
result = functionResult.getValue();

4. 配置与描述

准备发布

在构建APK之前,配置混淆脚本以防止AppGallery Connect SDK被混淆。如果出现混淆,则AppGallery Connect SDK可能无法正常工作。有关更多信息,请参阅此Android开发者指南

&lt;flutter_project&gt;/android/app/proguard-rules.pro
-ignorewarnings
-keep class com.huawei.agconnect.**{*;}

# Flutter包装器
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.**  { *; }
-keep class io.flutter.util.**  { *; }
-keep class io.flutter.view.**  { *; }
-keep class io.flutter.**  { *; }
-keep class io.flutter.plugins.**  { *; }
-dontwarn io.flutter.embedding.**
-keep class com.huawei.hianalytics.**{*;}
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agconnect.**{*;}
-keep class com.huawei.agc.**{*;}
-repackageclasses
buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {

        // 启用代码压缩、混淆和优化以构建发行版
        minifyEnabled true
        // 删除未使用的资源,保留在res/raw/keep.xml中定义的资源。
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        signingConfig signingConfigs.config
    }
}

5. 示例项目

此插件在"example"文件夹中包含一个演示项目,您可以在此找到更多使用示例。

6. 许可和条款

AppGallery Connect Cloud Functions Kit Flutter插件根据Apache 2.0许可证授权。


示例代码

/*
 * Copyright (c) 2021-2023. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:agconnect_cloudfunctions/agconnect_cloudfunctions.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 云函数的HTTP触发器标识符,格式为函数名-版本号
  // 有关更多信息,请参阅https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/android-call-function-0000001071314156#section11652152615214
  final String _defaultFunctionIdentifier = 'testfunc-\$latest'; // 您的触发器句柄
  final String _defaultResultText = '更改函数名称并单击"调用函数"按钮以获取响应。';

  late TextEditingController _functionTextController;
  late TextEditingController _resultTextController;

  [@override](/user/override)
  void initState() {
    super.initState();
    _functionTextController = TextEditingController(text: _defaultFunctionIdentifier);
    _resultTextController = TextEditingController(text: _defaultResultText);
  }

  [@override](/user/override)
  void dispose() {
    _functionTextController.dispose();
    _resultTextController.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AGC Cloud Functions Example'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(16),
          physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
          children: <Widget>[
            TextField(
              controller: _functionTextController,
              textAlign: TextAlign.center,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  child: const Text('调用函数'),
                  onPressed: () async {
                    try {
                      final FunctionCallable functionCallable = FunctionCallable(_functionTextController.text);
                      final FunctionResult functionResult = await functionCallable.call(
                        const <String, dynamic>{
                          'number1': 10,
                          'number2': 15,
                        },
                      );
                      setState(() => _resultTextController.text = functionResult.getValue());
                    } on PlatformException catch (e) {
                      setState(() => _resultTextController.text = FunctionError.fromException(e).toJson());
                    }
                  },
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  child: const Text('重置'),
                  onPressed: () {
                    setState(() {
                      _functionTextController.text = _defaultFunctionIdentifier;
                      _resultTextController.text = _defaultResultText;
                    });
                  },
                ),
              ],
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _resultTextController,
              maxLines: null,
              readOnly: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter云函数调用插件agconnect_cloudfunctions的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter云函数调用插件agconnect_cloudfunctions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,使用agconnect_cloudfunctions插件可以方便地调用华为AGC(AppGallery Connect)云函数。以下是如何使用该插件的步骤:

1. 添加依赖

首先,在pubspec.yaml文件中添加agconnect_cloudfunctions依赖:

dependencies:
  flutter:
    sdk: flutter
  agconnect_cloudfunctions: ^1.6.0+300

然后,运行flutter pub get来安装依赖。

2. 初始化AGC

在使用云函数之前,需要先初始化AGC SDK。通常在main.dart中进行初始化:

import 'package:agconnect_cloudfunctions/agconnect_cloudfunctions.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化AGC SDK
  await AGCCloudFunctions.instance.initialize();
  
  runApp(MyApp());
}

3. 调用云函数

使用AGCCloudFunctions实例可以调用云函数。假设你已经在AGC控制台上创建了一个名为myCloudFunction的云函数,可以通过以下方式调用它:

import 'package:agconnect_cloudfunctions/agconnect_cloudfunctions.dart';

Future<void> callMyCloudFunction() async {
  try {
    // 调用云函数
    final response = await AGCCloudFunctions.instance.call("myCloudFunction", data: {
      "param1": "value1",
      "param2": "value2",
    });
    
    // 处理响应
    print("Response from cloud function: ${response.data}");
  } catch (e) {
    print("Error calling cloud function: $e");
  }
}
回到顶部