Flutter Plugin:Flutter插件
特殊的Package。提供Android或者iOS的底层封装,在Flutter层提供组件功能,使Flutter可以较方便的调取Native的模块。对于Flutter实现起来比较复杂的部分,都可以封装成Plugin。
AppDelegate -> FlutterViewController -> iOS Platform API(及第三方依赖)
Activity -> FlutterView -> Android Platform API(及第三方依赖)
原理图
_channel.invokeMethod
发起一次请求,onMethodCall
方法回被调用,该方法有两个参数:MethodCall call
:请求本身Result result
:结果处理方法call.method
可以知道 _channel.invokeMethod 中的方法名
,然后通过 result.success
回调返回成功结果响应
flutter_plugin
的 channel,然后去 handleMethodCall
,同样的通过 call.method
拿到方法名,通过 result
做出响应.
flutter create --template=plugin flutter_plugin
如果想支持swift或者kotlin,可以用如下命令进行创建:
flutter create --org com.example --plugin -i swift -a kotlin flutter_text_plugin
项目的组织结构如下
root
android
example
ios
lib
...
修改 example/lib/main.dart 代码
class FlutterPlugin {
...
static int calculate (int a, int b) {
return a + b;
}
}
class _MyAppState extends State {
String _platformVersion = 'Unknown';
///1. 定义一个 int 型变量,用于保存计算结果
int _calculateResult;
@override
void initState() {
super.initState();
initPlatformState();
}
Future initPlatformState() async {
String platformVersion;
try {
platformVersion = await Wechat.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
///2. init 的时候,计算一下 6 + 6 的结果
_calculateResult = FlutterPlugin.calculate(6, 6);
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Container(
padding: EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Column(
children: [
Text('Running on: $_platformVersion\n'),
///3. 输出该结果
Text('Calculate Result: $_calculateResult\n'),
],
),
),
),
),
);
}
}
效果图
测试效果图
很多时候,写插件,更多的是因为我们需要让应用能够调用原生代码提供的方法
打开 /android/src/main/java/com/example/flutter_plugin/FlutterPlugin.java
文件
package com.example.flutter_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;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
/** FlutterPlugin */
public class FlutterPlugin implements MethodCallHandler {
/** Plugin registration. */
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_plugin");
channel.setMethodCallHandler(new FlutterPlugin());
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else if (call.method.equals("calculate")) {
int a = call.argument("a");
int b = call.argument("b");
int r = a + b;
result.success("" + r);
} else if (call.method.equals("register")) {
appid = call.argument("appid");
api = WXAPIFactory.createWXAPI(context, appid, true);
result.success(api.registerApp(appid));
} else {
result.notImplemented();
}
}
}
打开 ios/Classes/FlutterPlugin.m
文件
#import "FlutterPlugin.h"
@implementation FlutterPlugin
+ (void)registerWithRegistrar:(NSObject*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"flutter_plugin"
binaryMessenger:[registrar messenger]];
FlutterPlugin* instance = [[FlutterPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
NSDictionary *arguments = [call arguments];
if ([@"getPlatformVersion" isEqualToString:call.method]) {
result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
} else if ([@"calculate" isEqualToString:call.method]) {
NSInteger a = [arguments[@"a"] intValue];
NSInteger b = [arguments[@"b"] intValue];
result([NSString stringWithFormat:@"%d", a + b]);
}else if ([@"register" isEqualToString:call.method]) {
[WXApi registerApp:arguments[@"appid"]];
result(nil);
}else {
result(FlutterMethodNotImplemented);
}
}
@end
lib/flutter_plugin.dart
中修改方法实现
import 'dart:async';
import 'package:flutter/services.dart';
class FlutterPlugin {
static const MethodChannel _channel =
const MethodChannel('flutter_plugin');
static Future get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
static Future calculate (int a, int b) async {
final String result = await _channel.invokeMethod('calculate', {
'a': a,
'b': b
});
return int.parse(result);
}
/// Register app to Wechat with [appid]
static Future register(String appid) async {
var result = await _channel.invokeMethod(
'register',
{
'appid': appid
}
);
return result;
}
}
main.dart
中使用
///2. init 的时候,计算一下 6 + 6 的结果
_calculateResult = await FlutterPlugin.calculate(6, 6);
FlutterPlugin.register('appId');
4.1-Android
android/build.gradle
文件 ,在最下方粘贴以上片段即可
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
}
}
rootProject.allprojects {
repositories {
google()
jcenter()
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 27
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
lintOptions {
disable 'InvalidPackage'
}
}
dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}
else if (call.method.equals("register")) {
appid = call.argument("appid");
api = WXAPIFactory.createWXAPI(context, appid, true);
result.success(api.registerApp(appid));
}
static Future register(String appid) async {
var result = await _channel.invokeMethod(
'register',
{
'appid': appid
}
);
return result;
}
4.2-iOS
s.dependency 'WechatOpenSDK'
)
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'flutter_plugin'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.dependency 'WechatOpenSDK'
s.ios.deployment_target = '8.0'
end
#import
#include "WXApi.h"
@interface WechatPlugin : NSObject
@end
else if ([@"register" isEqualToString:call.method]) {
[WXApi registerApp:arguments[@"appid"]];
result(nil);
}
在发布之前,确保pubspec.yaml,、README.md以及CHANGELOG.md文件的内容都正确填写完毕。可以通过dry-run
命令来看准备是否就绪
。
flutter packages pub publish --dry-run
检查无误后,可以执行下面的命令,发布到Pub上。
flutter packages pub publish
dependencies:
flutter_plugin: ^0.0.1
如果这个库包含了一些平台相关的东西,例如需要在native层进行使用的话,则需要在对应的native项目单独做引用
1.1-Android
修改android/build.gradle的dependencies处做引用:
dependencies {
provided rootProject.findProject(":url_launcher")
}
1.2-iOS
修改.podspec
文件
Pod::Spec.new do |s|
# lines skipped
s.dependency 'flutter_plugin'
引用未发布的库有两种方式,通过本地路径和git地址的方式:
2.1-基于Path的引用方式:
这种方式主要针对本地的未发布的库,引用的路径可以是相对或者绝对路径。
dependencies:
plugin1:
path: ../plugin1/
2.2-基于Git的引用方式:
这种方式针对存放在git上的库,其中path是可选的,可以定位到某个子目录
dependencies:
package1:
git:
url: git://github.com/flutter/packages.git
path: packages/package1
引用不同的库可能会导致一些冲突,例如A和B两个插件,都包含了C插件,但是所需的版本不同。因此我们可以采取以下措施避免这种问题:
force
命令强制指定版本,而iOS这边,Cocoapods则不支持引用的override功能
。解决办法:project目录/example/pubspec.yaml
该目录添加version 字段即可version: 0.0.1
效果图
flutter create --org com.example --template=plugin flutter_demo
flutter create --org com.example --template=plugin -i objc -a java flutter_demo
flutter create --org com.example --template=plugin -i swift -a kotlin flutter_demo
作者:StevenHu_Sir
链接:https://www.jianshu.com/p/4bf045fd21f5
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。