用Flutter开发自定义Plugin的方法示例
作者:zyangdev 发布时间:2023-07-05 00:19:40
当你在开发flutter应用的时候,有时会需要调用native的api,往往遇到flutter并没有相应的package, 这时候flutter plugin就开始发挥作用了,这篇文章将会讲解开发一个简单flutter plugin的步骤和方法,好了,让我们开始动手吧。
1.在Android Studio 中创建一个Flutter Plugin 项目,如下图
上图中你能看到项目描述中写到,如果需要暴露Andorid或iOS的API给开发者时,选择"Plugin"项目类型。
这个项目我们命名为:flutter_native_log_plugin, 当我们完成创建项目后,有两个文件我们需要看一看, 一个是位于android/src下的FlutterNativeLogPlugin.java, 这段代码是用来和本地设备交互,然后将交互结果返回供flutter前端调用, 如下所示:
package com.cube8.flutter_native_log_plugin;
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;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/** FlutterNativeLogPlugin */
public class FlutterNativeLogPlugin implements MethodCallHandler {
/** Plugin registration. */
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(),
"flutter_native_log_plugin");
channel.setMethodCallHandler(new FlutterNativeLogPlugin());
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
}
另一个 /lib/mian.dart文件,这段代码是主要用来和native代码交互, 如下所示:
import 'dart:async';
import 'package:flutter/services.dart';
class FlutterNativeLogPlugin {
static const MethodChannel _channel =
const MethodChannel('flutter_native_log_plugin');
static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
}
2.现在我们开始编写我们的Plugin.
在lib/flutter_native_log_plugin.dart 文件中,我们先创建一个新的方法,代码如下:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
enum Log { DEBUG, WARNING, ERROR }
class FlutterNativeLogPlugin {
static const MethodChannel _channel =
const MethodChannel('flutter_native_log_plugin');
static Future<String> printLog(
{Log logType, @required String tag, @required String msg}) async {
String log = "debug";
if (logType == Log.WARNING) {
log = "warning";
} else if (logType == Log.ERROR) {
log = "error";
} else {
log = "debug";
}
final Map<String, dynamic> params = <String, dynamic>{
'tag': tag,
'msg': msg,
'logType': log
};
final String result = await _channel.invokeMethod('printLog', params);
return result;
}
}
在Android端,我们将android/src下的FlutterNativePlugin.java改写如下:
package com.cube8.flutter_native_log_plugin;
import android.util.Log;
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;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/**
* FlutterNativeLogPlugin
*/
public class FlutterNativeLogPlugin implements MethodCallHandler {
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_native_log_plugin");
channel.setMethodCallHandler(new FlutterNativeLogPlugin());
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("printLog")) {
String msg = call.argument("msg");
String tag = call.argument("tag");
String logType = call.argument("logType");
if (logType.equals("warning")) {
Log.w(tag, msg);
} else if (logType.equals("error")) {
Log.e(tag, msg);
} else {
Log.d(tag, msg);
}
result.success("Logged Successfully!");
} else {
result.notImplemented();
}
}
}
3.测试plugin。当开发完了我们的plugin之后,我们需要测试这个新plugin是否可用,于是对example/lib的main.dart文件作如下修改:
import 'package:flutter/material.dart';
import 'package:flutter_native_log_plugin/flutter_native_log_plugin.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
void printLogs() async {
print(await FlutterNativeLogPlugin.printLog(
tag: "Debug", msg: "This is ordinary Log")); // default logType
print(await FlutterNativeLogPlugin.printLog(
tag: "Debug",
msg: "This is warning Log",
logType: Log.WARNING)); // logType = warning
print(await FlutterNativeLogPlugin.printLog(
tag: "Debug",
msg: "This is error Log",
logType: Log.ERROR)); // logType = error
print(await FlutterNativeLogPlugin.printLog(
tag: "Debug",
msg: "This is debug Log",
logType: Log.DEBUG)); // logType = debug
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: RaisedButton(
child: Text("PrintLogs"),
onPressed: printLogs,
),
),
),
);
}
}
点击app中的按钮,控制台将看到如下输出,说明plugin可以顺利运行了。
4.最后一步就是将我们开发的plugin发布到dart pub供以后直接调用。打开控制台,需要确认定位到plugin项目的根目录,然后输入如下命令:
flutter packages pub publish --dry-run
这段命令会做一个程序相关文件和信息的检查,确保待发布的plugin信息完整,根据控制台的提示完善信息后,与下图相似:
接着输入如下命令,正式将plugin发布到dart pub中:
flutter packages pub publish
来源:https://segmentfault.com/a/1190000019488195


猜你喜欢
- WebService是一种传统的SOA技术架构,它不依赖于任何的编程语言,也不依赖于任何的技术平台,可以直接基于HTTP协议实现网络应用间的
- 先附上图片上传的代码jsp代码如下:<form action="${path}/upload/uploadPic.do&qu
- 前言本文主要给大家介绍了关于利用Spring Data MongoDB持久化文档数据的相关内容,分享出来供大家参考学习,下面话不多说了,来一
- spring的事务控制本质上是通过aop实现的。在springboot中使用时,可以通过注解@Transactional进行类或者方法级别的
- 本文实例讲述了C#静态构造函数用法。分享给大家供大家参考。具体如下:当我们想初始化一些静态变量的时候,就需要用到静态构造函数了。这个静态构造
- Java反射动态修改注解的某个属性值昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。这个题目我并不是很熟悉,不过
- 在线程间通信方式中,我们了解到可以使用Semaphore信号量来实现线程间通信,Semaphore支持公平锁和非公平锁,Semaphore底
- 前面已经把java io的主要操作讲完了 这一节我们来说说关于java io的其他内容 Serializable序列化 实例1:对象的序列化
- 准备:(1) IDEA 2021(2)Java 1.8(3)数据库 MySQL 5.7 (SQLyog 或 Navicat)在 MySQL
- 一、观察者模式基本概况1.概念观察者模式(Observer Design Pattern)也被称为发布订阅模式(Publish-Subcri
- 前面文章介绍了如何使用JAVA的反射机制来调用蓝牙的隐藏API,本文继续来练习JAVA的反射机制,探秘TelephonyManager在Fr
- 下面通过一段内容有文字说明有代码分析,并附有展示图供大家学习。要解析HTTP报文,需要实现以下操作:读取HTTP报头提供的各种属性分析属性值
- 值传递:(形式参数类型是基本数据类型):方法调用时,实际参数把它的值传递给对应的形式参数,形式参数只是用实际参数的值初始化自己的存储单元内容
- 从个小例子开始: int[] intArray = new int[]{2,3,6,1,4,5}; Array.Sort(intArray)
- 写在前面从Java 1.0开始,引入java.io包;到Java 1.4再扩展了java.nio包;再到java 1.7又添加了新的流类,使
- 一、File类1、简介java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关 File 能新建、删除、重命名文件和目录,但
- 这篇文章主要介绍了JavaMail与Spring整合过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需
- 介绍大家都知道微信支付的回调链接要求不能跟参数,但又要接收返回的xml数据。我开始使用@RequestBody注解在参数上,希望能获取xml
- 问题描述Feign 在请求时是不会将 request 的请求头带着请求的,导致假如 Feign 调用的接口需要请求头的信息,比如当前用户的
- 关于这个的例子其实网上已经有这方面的资料了,但是为了文章的完整性,还是觉得有必要讲解.我们先来看一下效果: