Flutter Windows平台通道异常:调用方法仅返回true而非预期字符串
Flutter Windows MethodChannel 返回异常问题修复
问题分析
你的代码中存在三个关键错误,导致调用test方法时返回true而非预期字符串:
- 重复定义局部
channel变量:第一个channel引用了未定义的FlEngine,随后又重新定义channel,属于冗余错误代码。 - 局部
channel生命周期过短:initMethodChannel中的channel是局部变量,函数执行完毕后会被销毁,导致MethodChannel实例被释放,注册的方法处理器随之失效。 - 未声明的
res变量:res = flutter::EncodableValue("Channel is working!");中的res未提前声明,会引发编译错误(若你能运行,大概率是代码书写失误)。
修复步骤
1. 修改flutter_window.h,添加MethodChannel成员变量
在FlutterWindow类中添加私有成员,用于保存MethodChannel实例:
class FlutterWindow : public Win32Window { public: // ... 原有代码 ... private: // ... 原有代码 ... std::unique_ptr<flutter::MethodChannel<>> method_channel_; void initMethodChannel(flutter::FlutterEngine* flutter_instance); };
2. 修正flutter_windows.cpp中的initMethodChannel函数
将全局函数改为类成员函数,移除冗余代码,直接在Success回调中传入字符串值:
void FlutterWindow::initMethodChannel(flutter::FlutterEngine* flutter_instance) { const static std::string channel_name("test_channel"); method_channel_ = std::make_unique<flutter::MethodChannel<>>( flutter_instance->messenger(), channel_name, &flutter::StandardMethodCodec::GetInstance()); method_channel_->SetMethodCallHandler( [](const flutter::MethodCall<>& call, std::unique_ptr<flutter::MethodResult<>> result) { if (call.method_name() == "test") { // 直接传入EncodableValue,无需额外变量 result->Success(flutter::EncodableValue("Channel is working!")); } else { result->NotImplemented(); } } ); }
3. 修正OnCreate中的函数调用
将原来的全局函数调用改为类成员调用:
bool FlutterWindow::OnCreate() { // ... 原有代码 ... RegisterPlugins(flutter_controller_->engine()); // 调用类成员方法 this->initMethodChannel(flutter_controller_->engine()); // ... 原有代码 ... }
4. 移除冗余错误代码
删除initMethodChannel中原有的无效代码:
// 删除以下两行冗余代码 flutter::BinaryMessenger *messenger = FlEngine->messenger(); const flutter::StandardMethodCodec *codec = &flutter::StandardMethodCodec::GetInstance(); auto channel = std::make_unique<flutter::MethodChannel<>>(messenger ,channel_name ,codec);
修复效果
重新编译运行后,Dart端调用:
MethodChannel channel = const MethodChannel('test_channel'); print(await channel.invokeMethod("test"));
将输出预期结果:
flutter: Channel is working!
内容的提问来源于stack exchange,提问作者Ali A.M.Hassani
相关产品推荐
相关产品推荐

