Flutter Plugin简单开发

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

新建项目

image-20230302134808397.png
image-20230302135317486.png

项目结构

image-20230302135906299.png

创建完成后的目录如图所示,其中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

3381990-64a2e818780d689a.png

2、打开后的界面如下

image-20230302141536195.png

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

无参方法的调用

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

Future<String?> hello(){
  throw UnimplementedError('hello() has not been implemented.');
}

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

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

3、在flutter_plugin.dart中调用

Future<String?> 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});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String? _msg;
  final _flutterPlugin = FlutterPlugin();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> 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;
    });
  }

  @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")),
            ],
          ),
        ),
      ),
    );
  }
}

6、测试结果

image-20230302142948784.png

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

有参方法的调用

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

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

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

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

3、在flutter_plugin.dart中调用

Future<String?> 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 Map<String, String>
      result.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<String?> hey(String message){
  throw UnimplementedError('hey() has not been implemented.');
}

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

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

3、在flutter_plugin.dart中调用

Future<String?> 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 Map<String, String>
      result.success("Android invoke==>hi(${param["message"]})")
    }
    "hey" -> {
      val param = call.arguments as Map<String, String>
      val response = mutableMapOf<String, String>()
      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<String?> event(){
  throw UnimplementedError('event() has not been implemented.');
}

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

late StreamSubscription<dynamic> _eventSubscription;

MethodChannelFlutterPlugin() {
  _initEvent();
}

void _initEvent() {
  _eventSubscription = _eventChannel()
    .receiveBroadcastStream()
    .listen((event) {
      final Map<dynamic,dynamic> 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<String?> event() async{
  final msg =
    await methodChannel.invokeMethod<Map<dynamic, dynamic>>('event');
  return msg?["message"];
}

3、在flutter_plugin.dart中调用

Future<String?> 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 Map<String, String>
      result.success("Android invoke==>hi(${param["message"]})")
    }
    "hey" -> {
      val param = call.arguments as Map<String, String>
      val response = mutableMapOf<String, String>()
      response["message"] = "Android invoke==>hey(${param["message"]})"
      result.success(response)
    }
    "event" -> {
      if (eventSink != null) {
        val response = mutableMapOf<String, String>()
        response["event"] = "demoEvent"
        response["message"] = "Android invoke==>event"
        eventSink?.success(response)
      }
      val response = mutableMapOf<String, String>()
      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<String?> 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<String?> alert(String message) {
  _showAlert(msg: message);
  return Future(() => message);
}

/// [injectCssAndJSLibraries] which add the JS and CSS files into DOM
Future<void> injectCssAndJSLibraries() async {
  final List<Future<void>> loading = <Future<void>>[];
  final List<html.HtmlElement> tags = <html.HtmlElement>[];

  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", "<br />");
  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<String?> 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<bool?> 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<bool?> 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", "<br />");
  html.Element? ele = html.querySelector("#copy-html");
  String content = """
     <div class="input_wrap">
        <input id="input_cp" type="text" readonly="true" value='$m'>
     </div>
        """;
  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", "<br />");
  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<bool?> 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()"))
          ],
        ),
      ),
    ),
  );
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容