用Flutter开发自定义Plugin的方法示例

作者:zyangdev 时间:2023-07-05 00:19:40 

当你在开发flutter应用的时候,有时会需要调用native的api,往往遇到flutter并没有相应的package, 这时候flutter plugin就开始发挥作用了,这篇文章将会讲解开发一个简单flutter plugin的步骤和方法,好了,让我们开始动手吧。

1.在Android Studio 中创建一个Flutter Plugin 项目,如下图

用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,
    ),
   ),
  ),
 );
}
}

用Flutter开发自定义Plugin的方法示例

点击app中的按钮,控制台将看到如下输出,说明plugin可以顺利运行了。

用Flutter开发自定义Plugin的方法示例

4.最后一步就是将我们开发的plugin发布到dart pub供以后直接调用。打开控制台,需要确认定位到plugin项目的根目录,然后输入如下命令:


flutter packages pub publish --dry-run

这段命令会做一个程序相关文件和信息的检查,确保待发布的plugin信息完整,根据控制台的提示完善信息后,与下图相似:

用Flutter开发自定义Plugin的方法示例

接着输入如下命令,正式将plugin发布到dart pub中:


flutter packages pub publish

来源:https://segmentfault.com/a/1190000019488195

标签:Flutter,Plugin
0
投稿

猜你喜欢

  • Java中静态代码块、构造代码块、构造函数和普通代码块的区别

    2023-11-25 10:09:06
  • Android中activity处理返回结果的实现方式

    2022-10-21 12:36:36
  • Android实现透明动画

    2023-02-08 04:45:47
  • 深入C#中get与set的详解

    2022-05-29 21:04:10
  • Spring IOC与DI核心重点分析

    2023-11-12 14:35:55
  • 完美解决gson将Integer默认转换成Double的问题

    2022-06-06 00:53:36
  • C# DataTable.Select()根据条件筛选数据问题

    2021-10-14 16:53:34
  • C#如何将DataTable导出到Excel解决方案

    2022-03-30 18:44:28
  • java写入文件的几种方法分享

    2023-06-26 15:56:55
  • java poi sax方式处理大数据量excel文件

    2021-09-19 19:28:48
  • Android实现小米相机底部滑动指示器

    2023-03-12 04:57:00
  • java 教你如何给你的头像添加一个好看的国旗

    2021-11-11 02:53:25
  • Android自定义控件的步骤

    2023-03-24 00:14:03
  • Android Studio finish()方法的使用与解决app点击“返回”(直接退出)

    2022-07-31 09:37:10
  • JavaWeb Servlet生命周期细枝末节处深究

    2023-08-25 22:48:23
  • 详解java整合solr5.0之solrj的使用

    2023-07-23 03:12:06
  • Java8时间api之LocalDate/LocalDateTime的用法详解

    2023-11-10 16:14:43
  • Java异常处理之try...catch...finally详解

    2023-09-17 05:38:24
  • Android Volley框架使用源码分享

    2023-09-10 09:43:44
  • spring boot自带图片服务器使用详解

    2021-11-07 07:49:39
  • asp之家 软件编程 m.aspxhome.com