首页 > 其他分享 >Flutter Plugin简单开发

Flutter Plugin简单开发

时间:2023-03-20 10:22:36浏览次数:58  
标签:plugin Plugin dart result 简单 msg message Flutter flutter

个人博客:
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<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

可以看出,成功调用到了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: () {}, one rror: (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()"))
          ],
        ),
      ),
    ),
  );
}

标签:plugin,Plugin,dart,result,简单,msg,message,Flutter,flutter
From: https://www.cnblogs.com/milovetingting/p/17235379.html

相关文章

  • 简单好用的图片取色器【可取RGB数值】
    前言没想到​​Snipaste​​​除了可以截图,还可以进行取色。可以使用​​Snipaste​​来进行颜色的提取。使用步骤1、按下快捷键F1,进行截图(可以修改快捷键截图的方式)2、选择......
  • 拖拽简单实现
    支持pc、移动、触摸屏js文件下载转载自简单图片拖拽-js插件,支持pc、移动、触摸屏1、使用<!--普通引入--><scriptsrc="./simpleImgDraggable.js"></script>//v......
  • JAVA -01(简单知识介绍)
    JAVA-01前期准备介绍1972年C诞生【两大问题:指针;内存管理】1982年C++诞生【面向对象;兼容C;图形领域和游戏,但是更复杂】1995年JAVA诞生【没有指针没有内存管理;面向对象......
  • SpringBoot+Vue+EasyExcel实现excel简单导入导出
    1.先导入EasyExcel依赖<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.......
  • 简单明了的体会构建者模式
    我们由一个小小的Demo来引出主题,尽管这个Demo有点长~~,我相信还是值得你一看的!木兰诗中有:“雄兔脚扑朔,雌兔眼迷离;双兔傍地走,安能辨我是雌雄?”对象之间的比较想必大家都很熟......
  • SSM整合 - 简单项目功能实现
    SSM整合练习创建数据库CREATEDATABASE`ssmbuild`;USE`ssmbuild`;DROPTABLEIFEXISTS`books`;CREATETABLE`books`( `bookID`INT(10)NOTNULLAUTO_INCRE......
  • ssh等简单使用
    ssh使用别名和实现免密登录ssh远程登录可以输入命令$sshuser_name@ip_addr/domain_name#usr_name是用户名,ip_addr是ip地址,domain_name是域名当不输入user_name的时候会......
  • flutter项目运行时一直卡在Running Gradle task 'assembleDebug'... & Could not reso
    先是看了别人的文章  Flutter项目启动一直卡在RunningGradletask‘assembleDebug‘问题解决-灰信网(软件开发博客聚合)(freesion.com),做了同样的处理,但接着又报错......
  • CSDN三道简单题:合并检测、星期一、特别数的和
    合并检测原题链接:https://edu.csdn.net/skill/practice/algorithm-6437a69f581f4821a5cbd4267304a905/2315新冠疫情由新冠病毒引起,最近在A国蔓延,为了尽快控制疫情,A国准......
  • Go语言 :使用简单的 for 迭代语句进行 TDD 驱动测试开发与 benchmark 基准测试
    前提准备与运行环境请参考:(新手向)在Linux中使用VScode编写"Hello,world"程序,并编写测试-Ubuntu20.4 在Go中for用来循环和迭代,Go语言没有while,do,until这几......