-
创建Androidstudio创建插件项目,注意project type选择Plugin
-
原生端实现FlutterPlugin, MethodCallHandler接口,并分别重写onAttachedToEngine,onDetachedFromEngine,onMethodCall方法,onAttachedToEngine方法内初始化MethodChannel对象,onMethodCall方法回调根据方法名判断flutter调用的是哪个方法,并进行相应逻辑处理,然后通过success方法将结果回传给flutter,具体实现案例如下:
class DeviceUtilsPlugin: FlutterPlugin, MethodCallHandler {
private lateinit var channel : MethodChannel
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "device_utils")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getDeviceVersion") {
result.success("Android 1.0.1")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
- flutter端继承PlatformInterface类,在此类定义你所需要的方法,具体实现案例如下:
abstract class DeviceUtilsPlatform extends PlatformInterface {
/// Constructs a BatteryUtilsPlatform.
BatteryUtilsPlatform() : super(token: _token);
static final Object _token = Object();
static DeviceUtilsPlatform _instance = MethodChannelDeviceUtils();
static DeviceUtilsPlatform get instance => _instance;
/// Platform-specific implementations should set this with their own
/// platform-specific class that extends [BatteryUtilsPlatform] when
/// they register themselves.
static set instance(DeviceUtilsPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
Future<String?> getDeviceVersion() {
throw UnimplementedError('getDeviceVersion() has not been implemented.');
}
}
- 定义MethodChannelDeviceUtils类,继承DeviceUtilsPlatform接口,在此类中创建MethodChannel对象,并重写DeviceUtilsPlatform方法,调用上述定义好的方法getDeviceVersion(),具体案例如下:
class MethodChannelDeviceUtils extends DeviceUtilsPlatform {
/// The method channel used to interact with the native platform.
@visibleForTesting
final methodChannel = const MethodChannel('device_utils');
@override
Future<String?> getDeviceVersion() async {
final version = await methodChannel.invokeMethod<String>('getDeviceVersion');
return version;
}
}
- 定义工具类,用于flutter调用插件方法
class BatteryUtils {
Future<String?> getDeviceVersion() {
return BatteryUtilsPlatform.instance.getDeviceVersion();
}
}
- 引用插件:分为打包上传到pub.dev和本地直接引用,打包上传先运行flutter pub publish --dry-run确保插件配置正确,之后执行flutter pub publish 发布插件,本地引用可以直接通过pubspec.yaml引用插件的绝对路径,具体引用案例如下所示:
device_utils:
path: C:\Users\xxxx\AndroidStudioProjects\device_utils