Android Flutter插件开发

背景说明

Flutter官方库支持力度有限(更多是ui框架对接平台native渲染服务),如果需要更多原生平台能力相关支持,比如相机、录音、查看设备信息等,需要手动开发插件支持(不同平台native提供实现,dart端提供接口并暴露出去)

1. 环境准备

AS2021.3.1
Flutter sdk 3.3.10

2. 创建Flutter Plugin项目

方式1:AS创建

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
这里直接点击finish之后可能报错

在这里插入图片描述
这时候如果用AS打开生成的项目会报错,原因未知

换成方式2

方式2:命令行创建

G:\MyWork\Flutter\Projects>G:\MyWork\Flutter\Tools\flutter\bin\flutter.bat create --org com.example --platforms=android,ios,windows --template=plugin flutter_plugin_demo
Flutter assets will be downloaded from https://storage.flutter-io.cn. Make sure you trust this source!
Creating project flutter_plugin_demo...
Running "flutter pub get" in flutter_plugin_demo...                907ms
Running "flutter pub get" in example...                            804ms
ERROR_ACCESS_DENIED file system exception thrown while trying to create a symlink from source to dest

G:\MyWork\Flutter\Tools\flutter\bin\flutter.bat create --org com.example --platforms=android,ios,windows --template=plugin flutter_plugin_demo

AS打开项目flutter_plugin_demo,此时正常显示

Flutter Plugin项目的目录结构

在这里插入图片描述

3. 添加插件功能

先看插件模块(对应1、3)

插件模块-android平台端(对应1)

只有一个类

在这里插入图片描述

插件模块-dart端(对应3)

在这里插入图片描述
在这里插入图片描述

再看插件使用模块(对应2)

怎么在pubspec.xml中引用插件模块看下一节”部署Flutter Plugin项目“

直接看dart端代码怎么调用

在这里插入图片描述

这里再举例插件使用模块怎么使用插件的,两种方式

在这里插入图片描述

总结:

以上是线上常用的插件模块开发方式

从插件使用方角度出发
跟直接用MethodChannel调用插件功能相比,插件模块发布并被引用更工程化,更优雅,使用插件的模块无需记住声明的插件名和插件方法,只需要调用dart实例对象方法即可

4. 发布Flutter Plugin项目

4.1 本地

两个pubspec文件,对应之前的4、5

插件模块的pubspec

在这里插入图片描述

  # This section identifies this Flutter project as a plugin project.
  # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
  # which should be registered in the plugin registry. This is required for
  # using method channels.
  # The Android 'package' specifies package in which the registered class is.
  # This is required for using method channels on Android.
  # The 'ffiPlugin' specifies that native code should be built and bundled.
  # This is required for using `dart:ffi`.
  # All these are used by the tooling to maintain consistency when
  # adding or updating assets for this project.

大致内容如下:
1.这是插件模块的声明段
2.pluginclass指明了原生能力的类(不同原生平台不同开发语言)
3.用来给插件使用模块注册插件用(其实flutter的android gradle编译插件在查找到插件模块声明了pluginclass的话就会动态反射生成一个类GeneratedPluginRegistrant)

插件使用模块的pubspec

在这里插入图片描述
这时候插件使用模块编译就会自动产生一个类GeneratedPluginRegistrant

在这里插入图片描述
这个类就是之前插件模块pubspec中声明的pluginclass,具体android平台类GeneratedPluginRegistrant实例化对象是由java层FlutterEngine初始化执行的,插件使用模块android端无需手写插件注册代码

总结

所以本地部署,要求使用插件方模块引用插件模块的根目录路径正确即可

4.2 pub官网发布

4.3 私有仓库发布

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值