文章目录
背景说明
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 私有仓库发布
略