-
example中main.dart布局
-
注意:FlutterPluginOne是在创建插件时根据名字来进行创建的,如下图:
具体内容如下:
class FlutterPluginOne {
// 这里的flutter_plugin_one字符串没有特殊要求,只需要和FlutterPluginOnePlugin.kt中的设置一样即可,即第4步
static const MethodChannel _channel =
const MethodChannel(‘flutter_plugin_one‘);
static Future<String?> get platformVersion async {
final String? version = await _channel.invokeMethod(‘getPlatformVersion‘);
return version;
}
// 显示Toast
static Future<void> showToast() async {
await _channel.invokeMethod("showToast");
}
// 通过get
static Future<void> get showToastByGet async {
await _channel.invokeMethod("showToast");
}
// 接受参数
static Future<void> showToastByMessage({String? message}) async {
Map param = Map<String,String>();
param["message"] = message ?? "showToastByMessage";
await _channel.invokeMapMethod("showToastByMessage",param);
}
}
-
插件项目下的android目录下:
-
FlutterPluginOnePlugin.kt中的内容如下:
/** FlutterPluginOnePlugin */ class FlutterPluginOnePlugin() : FlutterPlugin, MethodCallHandler { private lateinit var context: Context /// 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 methodChannel: MethodChannel private lateinit var eventChannel: EventChannel override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_plugin_one") methodChannel.setMethodCallHandler(this) context = flutterPluginBinding.applicationContext } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { if (call.method == "getPlatformVersion") { result.success("Android ${android.os.Build.VERSION.RELEASE}") } else if (call.method == "showToast") { Toast.makeText(context, "来自Android SDK中的Toast", Toast.LENGTH_SHORT) .show() } else if (call.method == "showToastByMessage") { val arguments = call.arguments as Map<*, *> Toast.makeText(context, arguments["message"] as String, Toast.LENGTH_SHORT) .show() } else { result.notImplemented() } } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { methodChannel.setMethodCallHandler(null) } }
-
当我们点击+按钮时,就会弹出“来自Android SDK中的Toast”内容。