怎么在Flutter中自定义Plugin
怎么在Flutter中自定义Plugin?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
1.在Android Studio 中创建一个Flutter Plugin 项目,如下图
上图中你能看到项目描述中写到,如果需要暴露Andorid或iOS的API给开发者时,选择"Plugin"项目类型。这个项目我们命名为:flutter_native_log_plugin, 当我们完成创建项目后,有两个文件我们需要看一看, 一个是位于android/src下的FlutterNativeLogPlugin.java, 这段代码是用来和本地设备交互,然后将交互结果返回供flutter前端调用, 如下所示:
packagecom.cube8.flutter_native_log_plugin; importio.flutter.plugin.common.MethodCall; importio.flutter.plugin.common.MethodChannel; importio.flutter.plugin.common.MethodChannel.MethodCallHandler; importio.flutter.plugin.common.MethodChannel.Result; importio.flutter.plugin.common.PluginRegistry.Registrar; /**FlutterNativeLogPlugin*/ publicclassFlutterNativeLogPluginimplementsMethodCallHandler{ /**Pluginregistration.*/ publicstaticvoidregisterWith(Registrarregistrar){ finalMethodChannelchannel=newMethodChannel(registrar.messenger(), "flutter_native_log_plugin"); channel.setMethodCallHandler(newFlutterNativeLogPlugin()); } @Override publicvoidonMethodCall(MethodCallcall,Resultresult){ 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'; classFlutterNativeLogPlugin{ staticconstMethodChannel_channel= constMethodChannel('flutter_native_log_plugin'); staticFuture<String>getplatformVersionasync{ finalStringversion=await_channel.invokeMethod('getPlatformVersion'); returnversion; } }
2.现在我们开始编写我们的Plugin.
在lib/flutter_native_log_plugin.dart 文件中,我们先创建一个新的方法,代码如下:
import'dart:async'; import'package:flutter/material.dart'; import'package:flutter/services.dart'; enumLog{DEBUG,WARNING,ERROR} classFlutterNativeLogPlugin{ staticconstMethodChannel_channel= constMethodChannel('flutter_native_log_plugin'); staticFuture<String>printLog( {LoglogType,@requiredStringtag,@requiredStringmsg})async{ Stringlog="debug"; if(logType==Log.WARNING){ log="warning"; }elseif(logType==Log.ERROR){ log="error"; }else{ log="debug"; } finalMap<String,dynamic>params=<String,dynamic>{ 'tag':tag, 'msg':msg, 'logType':log }; finalStringresult=await_channel.invokeMethod('printLog',params); returnresult; } }
在Android端,我们将android/src下的FlutterNativePlugin.java改写如下:
packagecom.cube8.flutter_native_log_plugin; importandroid.util.Log; importio.flutter.plugin.common.MethodCall; importio.flutter.plugin.common.MethodChannel; importio.flutter.plugin.common.MethodChannel.MethodCallHandler; importio.flutter.plugin.common.MethodChannel.Result; importio.flutter.plugin.common.PluginRegistry.Registrar; /** *FlutterNativeLogPlugin */ publicclassFlutterNativeLogPluginimplementsMethodCallHandler{ /** *Pluginregistration. */ publicstaticvoidregisterWith(Registrarregistrar){ finalMethodChannelchannel=newMethodChannel(registrar.messenger(),"flutter_native_log_plugin"); channel.setMethodCallHandler(newFlutterNativeLogPlugin()); } @Override publicvoidonMethodCall(MethodCallcall,Resultresult){ if(call.method.equals("printLog")){ Stringmsg=call.argument("msg"); Stringtag=call.argument("tag"); StringlogType=call.argument("logType"); if(logType.equals("warning")){ Log.w(tag,msg); }elseif(logType.equals("error")){ Log.e(tag,msg); }else{ Log.d(tag,msg); } result.success("LoggedSuccessfully!"); }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'; voidmain()=>runApp(MyApp()); classMyAppextendsStatefulWidget{ @override _MyAppStatecreateState()=>_MyAppState(); } class_MyAppStateextendsState<MyApp>{ @override voidinitState(){ super.initState(); } voidprintLogs()async{ print(awaitFlutterNativeLogPlugin.printLog( tag:"Debug",msg:"ThisisordinaryLog"));//defaultlogType print(awaitFlutterNativeLogPlugin.printLog( tag:"Debug", msg:"ThisiswarningLog", logType:Log.WARNING));//logType=warning print(awaitFlutterNativeLogPlugin.printLog( tag:"Debug", msg:"ThisiserrorLog", logType:Log.ERROR));//logType=error print(awaitFlutterNativeLogPlugin.printLog( tag:"Debug", msg:"ThisisdebugLog", logType:Log.DEBUG));//logType=debug } @override Widgetbuild(BuildContextcontext){ returnMaterialApp( home:Scaffold( appBar:AppBar( title:constText('Pluginexampleapp'), ), body:Center( child:RaisedButton( child:Text("PrintLogs"), onPressed:printLogs, ), ), ), ); } }
点击app中的按钮,控制台将看到如下输出,说明plugin可以顺利运行了。
4.最后一步就是将我们开发的plugin发布到dart pub供以后直接调用。打开控制台,需要确认定位到plugin项目的根目录,然后输入如下命令:
flutterpackagespubpublish--dry-run
这段命令会做一个程序相关文件和信息的检查,确保待发布的plugin信息完整,根据控制台的提示完善信息后,与下图相似:
接着输入如下命令,正式将plugin发布到dart pub中:
flutterpackagespubpublish
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注恰卡编程网行业资讯频道,感谢您对恰卡编程网的支持。