我在 Flutter App 内运行上了微信小程序

news/2024/7/20 3:10:32 标签: flutter, 微信小程序, 小程序

目前的疑惑

小程序>微信小程序发展的越来越快,目前小程序甚至取代了大部分 App 的生态位,公司的坑位不增反降,只能让原生应用开发兼顾或换岗进行小程序的开发。

以我的实际情况来讲,公司应用采用的 Flutter 框架,同样的功能不可避免的就会存在 Flutter 应用开发和小程序>微信小程序开发兼顾的情况,这种重复造轮子的工作非常低效。

为什么会存在这种情况?

随着 2019 年5月 Google I/O 上 Flutter 1.5.4 的发布,宣示着 Flutter 真正开始进入全终端时代,意味着只需要写一份代码,不需要任何额外的修正改,就可以运行在 iOS、Android、Web、PC 上。Flutter 正在革命性的改变移动开发的生态系统,从面向各个终端的开发,转向面向框架开发,不仅会改变开发者的开发方式,也有越来越多的公司开始关注使用 Flutter。

Flutter 作为一个跨平台的框架,其开发技术栈融合了 Native 和前端的技术,不仅涉及到了 Native(Android、iOS )的开发知识,又吸取了很多前端(例如 React)的技术理念和框架,并且在此基础上又有提升,形成 Flutter 自己独特的技术思维。

在这里插入图片描述

但目前来讲,Flutter 并不支持小程序,Flutter for Web 虽然最后也会生成 JS 代码,但是 Flutter 生成的 JS 和 CSS 都是不能修改的。而在 Flutter 中也没办法通过 Dart 直接调用小程序的接口,所以现阶段用 Flutter 开发小程序不是太好的选择。

一些解决思路的产生

但是公司和业务也不得不向着互联网巨头的流量低头,同时小程序的逐渐风靡,也使得用户下载 App 的习惯产生变化,不管购物、订餐还是办事都会首先查找“打开即用,即用即走”的小程序可以使用,省去了下载 App 的繁琐流程。

当然也知道很多开发者对于小程序是有非常多意见的,App 也不会说死就死,毕竟 App 相对于小程序来讲,还是有很多优势。所以 App 和小程序开发都共存的情况下,如何解决效率问题?

能否让过往开发的小程序直接运行在 Flutter 开发的应用中呢?同样一个功能业务仅需一次小程序开发,即可实现在除了微信端的其它 App 中也运行起来。

在 Google 找相关的解决方案和资料的时候,发现国外几乎没有这种方案,国内倒是有厂商在做这块,想想也确实符合情理。基于公司 Flutter 框架的基础现实情况下,名为 FinClip 小程序容器技术的产品是能够支持除原生 iOS、Android 之外的 Flutter 和 React Native ,并且能够直接兼容小程序>微信小程序语法,于是大概测试了下这个产品。

实操上手过程

原理其实挺简单的,FinClip 提供了小程序 SDK 给 Flutter 应用进行集成,这样以来 App 即拥有了一套可运行小程序业务代码的宿主环境。
在这里插入图片描述

1、获取凭据

集成 SDK 需要在 FinClip 平台中创建应用并绑定小程序,获得每个应用专属的 SDK KEY 及 SDK SECRET ,随后可以在集成 SDK 时填写对应的参数。打开小程序时 SDK 会自动初始化,并校验 SDK KEY,SDK SECRET 与BundleID (Application ID) 是否正确。

2、集成插件

在项目 pubspec.yaml 文件中添加依赖。

mop: latest.version 

如果电脑是 mac M1 芯片,还需要在 iOS 文件夹的 Podfile 文件增加以下3行代码

config.build_settings['ENABLE_BITCODE'] = 'NO'
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'

示例:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
      config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
    end
  end
end

3、Flutter API

在集成后,使用 SDK 提供的 API 之前必须要初始化 SDK 。下面我罗列官方的一些必要的 API ,更具体的也可以查阅官方文档。

1)初始化 sdk 接口

  ///
  ///
  /// initialize mop miniprogram engine.
  /// 初始化小程序
  /// [sdkkey] is required. it can be getted from api.finclip.com
  /// [secret] is required. it can be getted from api.finclip.com
  /// [apiServer] is optional. the mop server address. default is https://mp.finogeek.com
  /// [apiPrefix] is optional. the mop server prefix. default is /api/v1/mop
  /// [cryptType] is optional. cryptType, should be MD5/SM
  /// [disablePermission] is optional.
  /// [encryptServerData] 是否对服务器数据进行加密,需要服务器支持
  /// [userId] 用户id
  /// [finStoreConfigs] 多服务配置
  /// [uiConfig] UI配置
  /// [debug] 设置debug模式,影响调试和日志
  /// [customWebViewUserAgent] 设置自定义webview ua
  /// [appletIntervalUpdateLimit] 设置小程序批量更新周期
  /// [maxRunningApplet] 设置最大同时运行小程序个数
  ///
  Future<Map> initialize(
    String sdkkey,
    String secret, {
    String? apiServer,
    String? apiPrefix,
    String? cryptType,
    bool encryptServerData = false,
    bool disablePermission = false,
    String? userId,
    bool debug = false,
    bool bindAppletWithMainProcess = false,
    List<FinStoreConfig>? finStoreConfigs,
    UIConfig? uiConfig,
    String? customWebViewUserAgent,
    int? appletIntervalUpdateLimit,
    int? maxRunningApplet,
  }) 

2)打开小程序

 /// open the miniprogram [appId] from the  mop server.
  /// 打开小程序
  /// [appId] is required.
  /// [path] is miniprogram open path. example /pages/index/index
  /// [query] is miniprogram query parameters. example key1=value1&key2=value2
  /// [sequence] is miniprogram sequence. example 0,1.2.3,4,5...
  /// [apiServer] is optional. the mop server address. default is https://mp.finogeek.com
  /// [apiPrefix] is optional. the mop server prefix. default is /api/v1/mop
  /// [fingerprint] is optional. the mop sdk fingerprint. is nullable
  /// [cryptType] is optional. cryptType, should be MD5/SM
  Future<Map> openApplet(
    final String appId, {
    final String? path,
    final String? query,
    final int? sequence,
    final String? apiServer,
    final String? scene,
  }) 

3)获取当前正在使用的小程序信息

当前小程序信息包括的字段有appId,name,icon,description,version,thumbnail

  ///
  ///  get current using applet
  ///  获取当前正在使用的小程序信息
  ///  {appId,name,icon,description,version,thumbnail}
  ///
  ///
  Future<Map<String, dynamic>> currentApplet()

4)关闭当前打开的所有小程序

  ///
  /// close all running applets
  /// 关闭当前打开的所有小程序
  ///
  Future closeAllApplets()

4、官方示例

官方给了一个实例,我也直接放上来,大家可以参照下。

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:mop/mop.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
    @override
    _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
    @override
    void initState() {
        super.initState();
        init();
    }

    // Platform messages are asynchronous, so we initialize in an async method.
    Future<void> init() async {
        if (Platform.isIOS) {
            //com.finogeeks.mopExample
            final res = await Mop.instance.initialize(
                '22LyZEib0gLTQdU3MUauARlLry7JL/2fRpscC9kpGZQA', // SDK Key
                '1c11d7252c53e0b6', // SDK Secret
                apiServer: 'https://api.finclip.com', // 服务器地址
                apiPrefix: '/api/v1/mop' // 服务器接口请求路由前缀
                );
            print(res);
        } else if (Platform.isAndroid) {
            //com.finogeeks.mopexample
            final res = await Mop.instance.initialize(
                '22LyZEib0gLTQdU3MUauARjmmp6QmYgjGb3uHueys1oA', // SDK Key
                '98c49f97a031b555', // SDK Secret
                apiServer: 'https://api.finclip.com', // 服务器地址
                apiPrefix: '/api/v1/mop' // 服务器接口请求路由前缀
                );
            print(res);
        }
        if (!mounted) return;
    }

    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
            appBar: AppBar(
            title: const Text(' FinClip 小程序 Flutter 插件'),
        ),
            body: Center(
            child: Container(
            padding: EdgeInsets.only(
            top: 20,
        ),
            child: Column(
            children: <Widget>[
            Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    gradient: LinearGradient(
                        colors: const [Color(0xFF12767e), Color(0xFF0dabb8)],
                        stops: const [0.0, 1.0],
                    begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
            ),
        ),
            child: FlatButton(
            onPressed: () {
            Mop.instance.openApplet('5e3c147a188211000141e9b1'); // 小程序 AppID
        },
        child: Text(
            '打开示例小程序',
            style: TextStyle(color: Colors.white),
            ),
            ),
            ),
            SizedBox(height: 30),
            Container(
            decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            gradient: LinearGradient(
            colors: const [Color(0xFF12767e), Color(0xFF0dabb8)],
            stops: const [0.0, 1.0],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            ),
            ),
            child: FlatButton(
            onPressed: () {
            Mop.instance.openApplet('5e4d123647edd60001055df1', sequence: 1); // 小程序 AppID
            },
            child: Text(
            '打开官方小程序',
            style: TextStyle(color: Colors.white),
            ),
            ),
            ),
            ],
            ),
            ),
            ),
            ),
            );
            }
            }

最后的话

目前我是基于我个人的实际情况而找到的方案,如果大家有更好的方案也欢迎留言讨论交流。


http://www.niftyadmin.cn/n/47983.html

相关文章

企业电子招投标采购系统源码之首页设计

随着公司的快速发展&#xff0c;企业人员和经营规模不断壮大&#xff0c;公司对内部招采管理的提升提出了更高的要求。在企业里建立一个公平、公开、公正的采购环境&#xff0c;最大限度控制采购成本至关重要。符合国家电子招投标法律法规及相关规范&#xff0c;以及审计监督要…

Mybatis将参数作为查询字段或表名

在传入的参数作为select、create等后面的查询或创建列的字段名或表名时&#xff0c;一定要使用“${column}”的格式&#xff0c;而不能使用“#{column}”的格式。 #{}将传入的参数当成一个字符串&#xff0c;会给传入的参数加一个双引号${}将传入的参数直接显示生成在sql中&am…

Vue3配置路由(vue-router)

文章目录前言一、配置路由&#xff08;vue-router&#xff09;1、安装路由2、新建页面3、创建路由配置文件4.特殊报错&#xff01;前言 紧接上篇文章&#xff0c;vue3的配置与vue2是有所差别的&#xff0c;本文就讲述了如何配置&#xff0c;如果本文对你有所帮助请三连支持博主…

Hi3559av100平台8路1080P/720P输入配置流程梳理

平台&#xff1a; hi3559av100 硬件连接&#xff1a; 8路YUV422 -> 4路 2lane MIPI -> hi3559av100 最终效果&#xff1a; 经过处理后&#xff0c;后端可以实现8路独立视频流处理&#xff1b; 可以自由和后级VPSS/VENC/VO等模块进行绑定和处理 前言&#xff1a; &…

C语言--数据的存储1

目录数据类型的介绍类型的意义类型的基本归类整形家族浮点型家族构造类型--自定义类型指针类型空类型整形在内存中的存储大小端大小端如何区分为什么会有大小端判断机器字节序从本章开始&#xff0c;我们将正式进入C语言的进阶学习中。本篇内容我们将学习 数据的存储数据类型的…

力扣SQL刷题5

目录597. 好友申请 I&#xff1a;总体通过率602. 好友申请 II &#xff1a;谁有最多的好友603. 连续空余座位1045. 买下所有产品的客户597. 好友申请 I&#xff1a;总体通过率 官方讲的题目太繁琐了&#xff0c;大概就是&#xff08;表2中列1列2不全相同的行数&#xff09;/&a…

「ChatGPT」一夜之间“火爆出圈“【杞人忧天 or 未雨绸缪】

&#x1f482;作者简介&#xff1a; THUNDER王&#xff0c;一名热爱财税和SAP ABAP编程以及热爱分享的博主。目前于江西师范大学会计学专业大二本科在读&#xff0c;同时任汉硕云&#xff08;广东&#xff09;科技有限公司ABAP开发顾问。在学习工作中&#xff0c;我通常使用偏后…

VS各个版本对应的C++版本一览表(持续更新,最新为VS2022)

文章目录1、VS各版本与MSVC对照表2、GCC版本与C支持情况表3、VS版本与C支持情况表4、C#与.NET版本与C支持情况表5、引用官网地址&#xff1a;Visual Studio官网地址 可以查看主流C编译器支持的C标准&#xff1a;C 编译器支持情况表 1、VS各版本与MSVC对照表 IDE发布时间发布时…