欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-22 15:41:10
当你在开发flutter应用的时候,有时会需要调用native的api,往往遇到flutter并没有相应的package, 这时候flutter plugin就开始发挥作用...

当你在开发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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。