Flutter访问原生并带参数返回
Flutter 代码
FLUTTER_CALL_ANDROID为标识,通过这个标识判断该走哪个方法
CHANNEL_NAME为通道名
const MethodChannel _channel = const MethodChannel(CHANNEL_NAME);
在合适的位置使用方法
_channel.invokeMethod(FLUTTER_CALL_ANDROID).then((o) {
setState(() {
_topHeighRatio = o;
if (_topHeighRatio == null || _topHeighRatio < 0) {
_topHeighRatio = 0;
}
});
});
Android 代码
2020-02-08修正:
新版本的代码中getFlutterView()已经失效,修正为flutterEngine.getDartExecutor().getBinaryMessenger()
new MethodChannel(getFlutterView(), CHANNEL_NAME).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
// 通过methodCall可以获取参数和方法名 执行对应的平台业务逻辑即可
if (methodCall.method.equals(FLUTTER_CALL_ANDROID)) {
//ArrayList arrayList = (ArrayList) methodCall.arguments;
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
WindowManager.LayoutParams lp = getWindow().getAttributes();
float heightPixels = metric.heightPixels;
result.success(_topHeight / heightPixels);
new EventChannel(binaryMessenger, "send").setStreamHandler(streamHandle);
} else {
result.notImplemented();
}
}
}
);
Android 访问Flutter
Android代码
MESSAGE为标识
new EventChannel(binaryMessenger,MESSAGE).setStreamHandler(streamHandle);
参数
EventChannel.StreamHandler streamHandle = new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
eventSink.success("要传递的参数");
}
@Override
public void onCancel(Object o) {
}
};
BinaryMessenger binaryMessenger = new BinaryMessenger() {
@Override
public void send(String s, ByteBuffer byteBuffer) {
}
@Override
public void send(String s, ByteBuffer byteBuffer, BinaryReply binaryReply) {
}
@Override
public void setMessageHandler(String s, BinaryMessageHandler binaryMessageHandler) {
}
};
Flutter代码
EventChannel(MESSAGE)
.receiveBroadcastStream()
.listen((event){
print("It is Flutter - receiveBroadcastStream $event");
});