Flutter 与原生native通讯主要有:methodChannel、eventChannel、basicMessageChannel。
这里使用methodchannel
注意:目录结构
lib/
main.dart
windows/
Runner/
main.cpp
flutter_window.cpp
flutter_window.h
CMakeLists.txt
1、在flutter_window.h文件中:添加如下头文件
#include <flutter/event_channel.h>
#include <flutter/event_sink.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>
#include <windows.h>
2、在flutter_window.cpp文件中:添加头文件,
#include "flutter/generated_plugin_registrant.h"
并在bool FlutterWindow::OnCreate() {} 中添加如下代码:
RegisterPlugins(flutter_controller_->engine());
flutter::MethodChannel<> channel(
flutter_controller_->engine()->messenger(), "my_native_method_channel",
&flutter::StandardMethodCodec::GetInstance());
channel.SetMethodCallHandler(
[](const flutter::MethodCall<>& call,
std::unique_ptr<flutter::MethodResult<>> result) {
if (call.method_name() == "doSomething") {
//TODO
//在这里编写实现原生功能的代码
} else {
result->NotImplemented();
}
});
SetChildContent(flutter_controller_->view()->GetNativeWindow());
return true;
3、在main.dart文件中,
// 创建平台通道
static const platform = MethodChannel('my_native_method_channel');
//调用
void _doSomething()async{
await platform.invokeMethod("doSomething");
}
以上即在flutter中通过methodChannel调用windows原生能力的目录结构及示例,具体功能可根据自己需求在TODO中完成c++代码编写,调用windows系统api实现平台原生能力。