(本文只列出与Android Native的交互,iOS使用相同的Api,处理方式类似)。主要就是 MethodChannel的使用,因为native端和flutter端都有 methodChannel的setMethodCallHandler(),和invokeMethod()方法,所以两端都可以使用methodChannel进行通信。
Dart调用Native源码:
//Dart端源码
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
...
class _MyHomePageState extends State {
static const platform = const MethodChannel('samples.flutter.dev/battery');
// Get battery level.
}
// Get battery level.
String _batteryLevel = 'Unknown battery level.';
Future _getBatteryLevel() async {
String batteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
setState(() {
_batteryLevel = batteryLevel;
});
}
//Native端,Android Java.(Kotlin类似)。交互代码运行在mainThread主线程。
import io.flutter.app.FlutterActivity;
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;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
// Note: this method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
});
}
}
Native发送给flutter数据:(同样使用methodChannel机制)
//native 端。这里是Kotlin,Java类似。
const val CONNECTION_CHANNEL = "com.demo.flutter.connection"
val methodChannel = MethodChannel(flutterView, CONNECTION_CHANNEL)
methodChannel.setMethodCallHandler { methodCall, result ->
when (methodCall.method) {
"activityFinish" -> {
goBack() //关闭当前页面
result.success(null) //标识调用成功
}
"showToastMessage" -> showShortToast(methodCall.argument("message"))
}
}
//使用注册的方法channel调用dart端方法名称,并传递参数。
Handler().postDelayed({
methodChannel.invokeMethod("aaa", "c")
}, 5000);
//dart端
static const _platform = const MethodChannel("com.whitehorse.flutter.connection");
_AboutPageState() {
_platform.setMethodCallHandler((handler) {
switch (handler.method) {
case "aaa":
_platform.invokeMethod("showToastMessage", {"message": "您调用了dart里的方法"});
break;
}
});
}
void _goBack() {
// _platform.invokeMethod("activityFinish");
}
另一种方式,实现native flutter通信:
基于 EventChannel,使用事件流 event stream 驱动,更适合长久耗时的方法调用。
//Native端,android.
public class MainActivity extends FlutterActivity {
public static final String STREAM = "com.yourcompany.eventchannelsample/stream";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new EventChannel(getFlutterView(), STREAM).setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object args, final EventChannel.EventSink events) {
Log.w(TAG, "adding listener");
}
@Override
public void onCancel(Object args) {
Log.w(TAG, "cancelling listener");
}
}
);
}
}
//flutter,dart端
static const stream =
const EventChannel('com.yourcompany.eventchannelsample/stream');
StreamSubscription _timerSubscription = null;
void _enableTimer() {
if (_timerSubscription == null) {
_timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer); // 添加监听
}
}
void _disableTimer() {
if (_timerSubscription != null) {
_timerSubscription.cancel();
_timerSubscription = null;
}
}
* flutter receiveBroadcastStream([arguments]) 返回一个 broadcast stream对象。使用API进行操作。
https://api.flutter.dev/flutter/dart-async/Stream-class.html。
常用的为 listener。