uniapp
为了通信方便,封装了MethodChannel
源码:https://github.com/snice/uniapp-flutter/blob/main/js/flutter/flutter.js
import { MethodChannel } from '@/js/flutter/flutter.js';
let methodChannel = new MethodChannel('topMain'); // topMain 是 instanceId
方法:
$on
监听flutter发送的事件
methodChannel.$on('test', e => {
console.log('test', e);
if (e.callbackId) { // callbackId存在说明,需要回调数据
methodChannel.callback(e.callbackId, { result: 3 });
} else {
uni.showToast({
title: JSON.stringify(e),
icon: 'none'
});
}
});
$off
取消监听flutter发送的事件
methodChannel.$off('test');
$emit
向flutter发送消息
// 发送消息,无返回数据
methodChannel.$emit('test', { a: 3 });
// 发送消息,又返回数据
methodChannel.$emit('test', { a: 3 }, e => {
uni.showModal({
title: JSON.stringify(e)
});
});
callback
配合$on使用,给flutter传递回调数据
let callbackId = 'test';
methodChannel.callback(callbackId, { result: 3 });
flutter
为了方便通信,封装了UniappMethodChannel
源码:https://github.com/snice/uniapp-flutter-module/blob/master/lib/channel/uniapp.dart
方法:
以下代码示例中uniapp变量,来自https://github.com/snice/uniapp-flutter-module/blob/master/lib/common/global.dart
也就是UniappMethodChannel的全局实例
$on
监听uniapp发送的事件
uniapp.$on('test', (Map<String, dynamic> map) {
print('test:' + map.toString());
if (map.containsKey("callbackId")) {
uniapp.callback(map['callbackId'], {'a': 6});
}
});
$off
取消监听uniapp发送的事件
uniapp.$off('test');
$emit
向uniapp发送消息
uniapp.$emit('test', {'test': _counter});
$emitSync
向uniapp发送消息,需要返回值使用
var value = await uniapp.$emitSync('test', {'test': _counter});
print(value);