Flutter与原生的交互主要通过MethodChannel的方式
本文只列举两种形式的插件,掌握基础的插件写法,举一反三,例如我github项目中的高德定位,6.0以上权限申请等,还需要掌握iOS的的基础语言o c,swift才能编写iOS插件。
效果GIF
从Flutter界面跳转到原生,且带参数
1. 实现插件
public class FlutterPluginJumpToAct implements MethodChannel.MethodCallHandler {
public static String CHANNEL = "com.jzhu.jump/plugin";
static MethodChannel channel;
private Activity activity;
private FlutterPluginJumpToAct(Activity activity) {
this.activity = activity;
}
public static void registerWith(PluginRegistry.Registrar registrar) {
channel = new MethodChannel(registrar.messenger(), CHANNEL);
FlutterPluginJumpToAct instance = new FlutterPluginJumpToAct(registrar.activity());
//setMethodCallHandler在此通道上接收方法调用的回调
channel.setMethodCallHandler(instance);
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
//通过MethodCall可以获取参数和方法名,然后再寻找对应的平台业务,本案例做了2个跳转的业务
//接收来自flutter的指令oneAct
if (call.method.equals("oneAct")) {
//跳转到指定Activity
Intent intent = new Intent(activity, OneActivity.class);
activity.startActivity(intent);
//返回给flutter的参数
result.success("success");
}
//接收来自flutter的指令twoAct
else if (call.method.equals("twoAct")) {
//解析参数
String text = call.argument("flutter");
//带参数跳转到指定Activity
Intent intent = new Intent(activity, TwoActivity.class);
intent.putExtra(TwoActivity.VALUE, text);
activity.startActivity(intent);
//返回给flutter的参数
result.success("success");
}
else {
result.notImplemented();
}
}
}
2. 插件注册
需要在继承了FlutterActivity中的Activity注册
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
registerCustomPlugin(this);
}
private static void registerCustomPlugin(PluginRegistry registrar) {
FlutterPluginJumpToAct.registerWith(registrar.registrarFor(FlutterPluginJumpToAct.CHANNEL));
FlutterPluginCounter.registerWith(registrar.registrarFor(FlutterPluginCounter.CHANNEL));
}
}
3. 带参数跳转
//获取到插件与原生的交互通道
static const jumpPlugin = const MethodChannel('com.jzhu.jump/plugin');
Future<Null> _jumpToNative() async {
String result = await jumpPlugin.invokeMethod('oneAct');
print(result);
}
Future<Null> _jumpToNativeWithValue() async {
Map<String, String> map = { "flutter": "这是一条来自flutter的参数" };
String result = await jumpPlugin.invokeMethod('twoAct', map);
print(result);
}
参数解释
1. 传递的参数
参数可以不指定类型
Future<dynamic> invokeMethod(String method, [dynamic arguments]) async {
assert(method != null);
final dynamic result = await BinaryMessages.send(
name,
codec.encodeMethodCall(new MethodCall(method, arguments)),
);
if (result == null)
throw new MissingPluginException('No implementation found for method $method on channel $name');
return codec.decodeEnvelope(result);
}
2. 解析传递的参数
解析的参数是泛型
public <T> T arguments() {
return this.arguments;
}
public <T> T argument(String key) {
if (this.arguments == null) {
return null;
} else if (this.arguments instanceof Map) {
return ((Map)this.arguments).get(key);
} else if (this.arguments instanceof JSONObject) {
return ((JSONObject)this.arguments).opt(key);
} else {
throw new ClassCastException();
}
}
原生主动发送参数给Flutter
1. 实现插件
public class FlutterPluginCounter implements EventChannel.StreamHandler {
public static String CHANNEL = "com.jzhu.counter/plugin";
static EventChannel channel;
private Activity activity;
private FlutterPluginCounter(Activity activity) {
this.activity = activity;
}
public static void registerWith(PluginRegistry.Registrar registrar) {
channel = new EventChannel(registrar.messenger(), CHANNEL);
FlutterPluginCounter instance = new FlutterPluginCounter(registrar.activity());
channel.setStreamHandler(instance);
}
@Override
public void onListen(Object o, final EventChannel.EventSink eventSink) {
Observable.interval(1000, TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Long aLong) {
eventSink.success(aLong.intValue());
}
@Override
public void onError(Throwable e) {
eventSink.error("计时器异常", "异常", e.getMessage());
}
@Override
public void onComplete() {
}
});
}
@Override
public void onCancel(Object o) {
Log.i("FlutterPluginCounter", "FlutterPluginCounter:onCancel");
}
}
2. Flutter接收原生发送的参数
static const counterPlugin = const EventChannel('com.jzhu.counter/plugin');
StreamSubscription _subscription = null;
var _count;
@override
void initState() {
super.initState();
//开启监听
if(_subscription == null){
_subscription = counterPlugin.receiveBroadcastStream().listen(_onEvent,onError: _onError);
}
}
@override
void dispose() {
super.dispose();
//取消监听
if(_subscription != null){
_subscription.cancel();
}
}
void _onEvent(Object event) {
setState(() {
_count = event;
print("ChannelPage: $event");
});
}
void _onError(Object error) {
setState(() {
_count = "计时器异常";
print(error);
});
}