Flutter Plugin简单开发
创始人
2025-05-31 14:19:12

个人博客:
http://www.milovetingting.cn

新建项目

image-20230302134808397

image-20230302135317486

项目结构

image-20230302135906299

创建完成后的目录如图所示,其中example是测试工程,用来测试我们写的插件。lib目录下的文件,就是需要具体实现的。

flutter_plugin_platform_interface.dart文件就是我们定义接口的地方,flutter_plugin_method_channel.dart是对应AndoidIOS的文件,flutter_plugin_web.dart是对应web平台。

方法实现

AndroidIOS平台要分别实现flutter_plugin_platform_interface.dart定义的方法。这里以AndroidWeb为例,实现接口中的方法。

Android端

1、在android目录上点击右键,选择Flutter菜单下的Open Android module in Android Studio

image-20230302141024419

2、打开后的界面如下

image-20230302141536195

我们主要在FlutterPlugin这个文件的onMethodCall方法中做具体实现

无参方法的调用

1、在flutter_plugin_platform_interface.dart类中增加方法

Future hello(){throw UnimplementedError('hello() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法

@override
Future hello() async {final msg = await methodChannel.invokeMethod('hello');return msg;
}

3、在flutter_plugin.dart中调用

Future hello() {return FlutterPluginPlatform.instance.hello();
}

4、Android端实现

FlutterPlugin.kt

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {when (call.method) {"getPlatformVersion" -> {result.success("Android ${android.os.Build.VERSION.RELEASE}")}"hello" -> {result.success("Android invoke==>hello()")}else -> {result.notImplemented()}}
}

5、在Example中测试

main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';import 'package:flutter/services.dart';
import 'package:flutter_plugin/flutter_plugin.dart';void main() {runApp(const MyApp());
}class MyApp extends StatefulWidget {const MyApp({super.key});@overrideState createState() => _MyAppState();
}class _MyAppState extends State {String _platformVersion = 'Unknown';String? _msg;final _flutterPlugin = FlutterPlugin();@overridevoid initState() {super.initState();initPlatformState();}// Platform messages are asynchronous, so we initialize in an async method.Future initPlatformState() async {String platformVersion;// Platform messages may fail, so we use a try/catch PlatformException.// We also handle the message potentially returning null.try {platformVersion = await _flutterPlugin.getPlatformVersion() ?? 'Unknown platform version';} on PlatformException {platformVersion = 'Failed to get platform version.';}// If the widget was removed from the tree while the asynchronous platform// message was in flight, we want to discard the reply rather than calling// setState to update our non-existent appearance.if (!mounted) return;setState(() {_platformVersion = platformVersion;});}@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [Text('Running on: $_platformVersion\n'),Text('msg: ${_msg ?? ""}\n'),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hello();if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hello")),],),),),);}
}

6、测试结果

image-20230302142948784

可以看出,成功调用到了Android端的方法

有参方法的调用

1、在flutter_plugin_platform_interface.dart类中增加方法

Future hi(String message){throw UnimplementedError('hi() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法

@override
Future hi(String message) async {Map param = {};param["message"] = message;final msg = await methodChannel.invokeMethod('hi', param);return msg;
}

3、在flutter_plugin.dart中调用

Future hi(String message) {return FlutterPluginPlatform.instance.hi(message);
}

4、Android端实现

FlutterPlugin.kt

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {when (call.method) {"getPlatformVersion" -> {result.success("Android ${android.os.Build.VERSION.RELEASE}")}"hello" -> {result.success("Android invoke==>hello()")}"hi" -> {val param = call.arguments as Mapresult.success("Android invoke==>hi(${param["message"]})")}else -> {result.notImplemented()}}
}

5、在Example中测试

main.dart

@override
Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [Text('Running on: $_platformVersion\n'),Text('msg: ${_msg ?? ""}\n'),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hello();if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hello")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hi("hi");if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hi(msg)")),],),),),);
}
Map参数方法调用

1、在flutter_plugin_platform_interface.dart类中增加方法

Future hey(String message){throw UnimplementedError('hey() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法

@override
Future hey(String message) async {Map param = {};param["message"] = message;final msg =await methodChannel.invokeMethod>('hey', param);return msg?["message"];
}

3、在flutter_plugin.dart中调用

Future hey(String message) {return FlutterPluginPlatform.instance.hey(message);
}

4、Android端实现

FlutterPlugin.kt

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {when (call.method) {"getPlatformVersion" -> {result.success("Android ${android.os.Build.VERSION.RELEASE}")}"hello" -> {result.success("Android invoke==>hello()")}"hi" -> {val param = call.arguments as Mapresult.success("Android invoke==>hi(${param["message"]})")}"hey" -> {val param = call.arguments as Mapval response = mutableMapOf()response["message"] = "Android invoke==>hey(${param["message"]})"result.success(response)}else -> {result.notImplemented()}}
}

5、在Example中测试

main.dart

@override
Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [Text('Running on: $_platformVersion\n'),Text('msg: ${_msg ?? ""}\n'),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hello();if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hello")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hi("hi");if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hi(msg)")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hey("hey");if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hey(msg)")),],),),),);
}
事件处理

1、在flutter_plugin_platform_interface.dart类中增加方法

Future event(){throw UnimplementedError('event() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法

late StreamSubscription _eventSubscription;MethodChannelFlutterPlugin() {_initEvent();
}void _initEvent() {_eventSubscription = _eventChannel().receiveBroadcastStream().listen((event) {final Map map = event;switch(map["event"]){case "demoEvent":{String message = map["message"];if (kDebugMode) {print("demo event:$message");}}}}, onDone: () {}, onError: (err) {final PlatformException e = err;throw e;});
}EventChannel _eventChannel() {return const EventChannel("flutter_plugin_demo_event");
}@override
Future event() async{final msg =await methodChannel.invokeMethod>('event');return msg?["message"];
}

3、在flutter_plugin.dart中调用

Future event() {return FlutterPluginPlatform.instance.event();
}

4、Android端实现

FlutterPlugin.kt

// 事件派发对象
private var eventSink: (EventChannel.EventSink)? = null// 事件流
private val streamHandler = object : EventChannel.StreamHandler {override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {eventSink = events}override fun onCancel(arguments: Any?) {eventSink = null}}override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_plugin_demo")channel.setMethodCallHandler(this)//初始化事件val eventChannel =EventChannel(flutterPluginBinding.binaryMessenger, "flutter_plugin_demo_event")eventChannel.setStreamHandler(streamHandler)
}override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {when (call.method) {"getPlatformVersion" -> {result.success("Android ${android.os.Build.VERSION.RELEASE}")}"hello" -> {result.success("Android invoke==>hello()")}"hi" -> {val param = call.arguments as Mapresult.success("Android invoke==>hi(${param["message"]})")}"hey" -> {val param = call.arguments as Mapval response = mutableMapOf()response["message"] = "Android invoke==>hey(${param["message"]})"result.success(response)}"event" -> {if (eventSink != null) {val response = mutableMapOf()response["event"] = "demoEvent"response["message"] = "Android invoke==>event"eventSink?.success(response)}val response = mutableMapOf()response["message"] = "Android invoke==>event"result.success(response)}else -> {result.notImplemented()}}
}

5、在Example中测试

main.dart

@override
Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [Text('Running on: $_platformVersion\n'),Text('msg: ${_msg ?? ""}\n'),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hello();if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hello")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hi("hi");if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hi(msg)")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.hey("hey");if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用hey(msg)")),ElevatedButton(onPressed: () async {var msg = await _flutterPlugin.event();if (kDebugMode) {print('msg from android:$msg');setState(() {_msg = msg;});}},child: const Text("调用event()")),],),),),);
}

Web端

Alert

1、在flutter_plugin_platform_interface.dart类中增加方法

Future alert(String message){throw UnimplementedError('alert() has not been implemented.');
}

2、在项目根目录下新增assets文件夹,然后增加plugin.css,plugin.js文件,在plugin.js文件里加入以下代码

function showAlert(msg) {alert(msg);
}

3、在pubspec.yaml中增加以下配置

  assets:- assets/

4、在flutter_plugin_web.dart类中实现上面的方法

FlutterPluginWeb(){injectCssAndJSLibraries();
}@override
Future alert(String message) {_showAlert(msg: message);return Future(() => message);
}/// [injectCssAndJSLibraries] which add the JS and CSS files into DOM
Future injectCssAndJSLibraries() async {final List> loading = >[];final List tags = [];final html.LinkElement css = html.LinkElement()..id = 'plugin-css'..attributes = {"rel": "stylesheet"}..href = 'assets/packages/flutter_plugin/assets/plugin.css';tags.add(css);final html.ScriptElement script = html.ScriptElement()..async = true..src = "assets/packages/flutter_plugin/assets/plugin.js";loading.add(script.onLoad.first);tags.add(script);html.querySelector('head')!.children.addAll(tags);await Future.wait(loading);
}_showAlert({String msg = ""}) {_insertAlertJs(msg);
}_insertAlertJs(String msg) {String m = msg.replaceAll("'", "\\'").replaceAll("\n", "
");html.Element? ele = html.querySelector("#alert-js");String content = """showAlert('$m');""";if (html.querySelector("#alert-js") != null) {ele!.remove();}final html.ScriptElement scriptText = html.ScriptElement()..id = "alert-js"..innerHtml = content;html.querySelector('head')!.children.add(scriptText); }

5、在flutter_plugin.dart中调用

Future alert(String message) {return FlutterPluginPlatform.instance.alert(message);
}

6、在Example中测试

main.dart

@override
Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [//...ElevatedButton(onPressed: () async {var msg =await _flutterPlugin.alert("hello,web!");if (kDebugMode) {print('msg from web:$msg');setState(() {_msg = msg;});}},child: const Text("调用alert()")),],),),),);
}
Copy

1、在flutter_plugin_platform_interface.dart类中增加方法

Future copy(String message){throw UnimplementedError('copy() has not been implemented.');
}

2、在plugin.js文件里加入以下代码

function copy(msg) {const input = document.getElementById('input_cp');// 选择需要复制的文本input.focus();if (input.setSelectionRange) {input.setSelectionRange(0, input.value.length);} else {input.select();}try {const result = document.execCommand('copy');} catch (e) {console.err("复制失败,请重试~");}// 让输入框失去焦点input.blur();// 让移动端的输入键盘自动收回document.activeElement.blur();
}

3、在plugin.css文件中加入以下代码

.main {position: relative;
}.input_wrap {position: absolute;top: 0;left: 0;width: 1px;opacity: 0;overflow: hidden;user-select: none;
}.input_wrap input {width: 1px;resize: none;border: none;outline: none;user-select: none;color: transparent;background: transparent;
}

4、在flutter_plugin_web.dart类中实现上面的方法

@override
Future copy(String message) {_copy(msg: message);return Future(() => true);
}_copy({String msg = ""}) {_insertCopyHtml(msg);_insertCopyJs(msg);
}_insertCopyHtml(String msg) {String m = msg.replaceAll("'", "\\'").replaceAll("\n", "
");html.Element? ele = html.querySelector("#copy-html");String content = """
""";if (html.querySelector("#copy-html") != null) {ele!.remove();}final html.BodyElement scriptText = html.BodyElement()..id = "copy-html"..innerHtml = content;html.querySelector('body')!.children.add(scriptText); }_insertCopyJs(String msg) {String m = msg.replaceAll("'", "\\'").replaceAll("\n", "
");html.Element? ele = html.querySelector("#copy-js");String content = """copy('$m');""";if (html.querySelector("#copy-js") != null) {ele!.remove();}final html.ScriptElement scriptText = html.ScriptElement()..id = "copy-js"..innerHtml = content;html.querySelector('head')!.children.add(scriptText); }

5、在flutter_plugin.dart中调用

Future copy(String message) {return FlutterPluginDemoPlatform.instance.copy(message);
}

6、在Example中测试

main.dart

@override
Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Center(child: Column(children: [//...ElevatedButton(onPressed: () async {var result =await _flutterPlugin.copy("hello,web!!!");if (kDebugMode) {print('copy result:$result');setState(() {_msg = "copy result:$result";});}},child: const Text("调用copy()"))],),),),);
}

相关内容

热门资讯

[实测了解]“天天德州扑克开挂... 您好:天天德州扑克这款游戏可以开挂,确实是有挂的,需要了解加客服微信【6670747】很多玩家在这款...
玩家实测“哈糖大菠萝有没有透视... 您好:哈糖大菠萝这款游戏可以开挂,确实是有挂的,需要软件加微信【6355786】,很多玩家在哈糖大菠...
重大爆料“悟空大厅牛牛到底有挂... 您好:悟空大厅牛牛这款游戏可以开挂,确实是有挂的,需要软件加微信【8487422】很多玩家在这款游戏...
[重大来袭]“十三十三水开挂辅... [重大来袭]“十三十三水开挂辅助神器”!详细开挂教程您好:十三十三水这款游戏可以开挂,确实是有挂的,...
重大来袭“大唐互娱开挂教程方法... 您好:大唐互娱这款游戏可以开挂,确实是有挂的,需要了解加客服微信【6670747】很多玩家在这款游戏...