Flutter 与原生交互、与h5交互

878 阅读1分钟

1.原生交互(Platform Channel)

主要原理:flutter通过Platform Channel将数据编码,跨线程异步传递,native接受后以相同方式返回。

三种Channel:

  • BasicMessageChannel:传递字符串和半结构化数据
  • MethodChannel:方法调用(可传参数)
  • EventChannel:数据流通信

通常用MethodChannel,仅传数据可用BasicMessageChannel,用法如下

  • flutter中:
///定义系统字符串名字
static MethodChannel mainWindowChannel = const MethodChannel("mainWindowChannel");
///接收定义
///_handleMethodCallback
mainWindowChannel.setMethodHandler(_handleMethodCallback);

Future<dynamic> _handleMethodCallback(MethodCall call, int fromWindowId) async {
  if (call.method == "savePosition") {}}

///发送定义
///invokeMethod(函数名字,传递参数)
var result = await mainWindowChannel.invokeMethod("setPosition", <String, dynamic>{
  'left': 100,
  'top': 100,
  'width': 100,
  'height': 100,
});

  • c++中
void configMethodChannel(flutter::FlutterEngine* engine, HWND hwnd) {
	const std::string test_channel("mainWindowChannel");
	const flutter::StandardMethodCodec& codec = flutter::StandardMethodCodec::GetInstance();
	flutter::MethodChannel method_channel_(engine->messenger(), test_channel, &codec);

	method_channel_.SetMethodCallHandler([hwnd](const auto& call, auto result) {
		std::cout << "MainWindow method call" << std::endl;
		if (call.method_name().compare("setPosition") == 0) {
                 }
         }
   }
  • Android端
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.io/battery";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//创建方法通道 [见小节4.1]
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getBatteryLevel")) {
//调用android端的BatteryManager来获取电池电量信息
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
//将函数执行的成功结果回传到Flutter端
result.success(batteryLevel);
} else {
//将函数执行的失败结果回传到Flutter端
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
});
}
}

h5(js通信)

主要还是用到插件webview_flutter里面内置的通信方法,示例如下

flutter端:
void initState() {
   controller = WebViewController()
     ..setJavaScriptMode(JavaScriptMode.unrestricted)
     ..addJavaScriptChannel('channel', onMessageReceived: (message) {
         //根据 message 信息跳转
     })
     ..loadHtmlString(htmlString);

   super.initState();
 }
 
 js:channel.postMessage(调用方法名);