上篇文章Flutter Packages 开发(一)介绍了纯flutter插件的开发,这篇文章介绍Android平台插件的开发
添加Android平台支持
在hello_plugin目录下执行
flutter create --template=plugin --platforms=android .
之后会在该目录下生成android文件夹,里面会自动生成HelloPlugin.kt
package com.example.hello_plugin
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** HelloPlugin */
class HelloPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
//声明一下通道为 plugins.flutter.io/hello_plugin
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "plugins.flutter.io/hello_plugin")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
//默认实现了 getPlatformVersion 方法
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
在hello_plugin/pubspec.yaml文件中的flutter:下面添加插件声明
plugin:
platforms:
android:
package: com.example.hello_plugin
pluginClass: HelloPlugin
回到dart层hello_plugin.dart,dart通过channel.invokeMethod方法调用Android层方法
library hello_plugin;
import 'package:flutter/services.dart';
abstract class HelloPluginInterface{
int addOne(int value);
//声明跟Android层同名的方法
Future<String> getPlatformVersion();
}
class HelloPlugin extends HelloPluginInterface {
//声明一下通道为 plugins.flutter.io/hello_plugin
static const MethodChannel _channel = MethodChannel('plugins.flutter.io/hello_plugin');
@override
int addOne(int value) {
return value + 1;
}
@override
Future<String> getPlatformVersion() async {
//invokeMethod 里面的参数也需跟Android层方法同名
return await _channel.invokeMethod('getPlatformVersion', null);
}
}
main.dart中调用如下
void _getPlatformVersion() async{
String p = await helloPlugin.getPlatformVersion();
setState(() {
platformVersion = p;
});
}
网友评论