Flutter依赖于传递消息的方式使用特定平台的API:
1.应用程序Flutter通过平台通道向宿主发送消息
2.宿主监听平台通道并接受消息,之后可以使用平台API,并将响应发送回客户端。
注 :消息和响应以异步形式进行传递,以确保用户界面保持响应
Flutter定义了三种Channel
BasicMessageChannel:用于传递字符串和半结构化的信息
MethodChannel:用于传递方法调用
EventChannel:用于数据流的通信
这里介绍通过MethodChannel通信的示例:
Flutter端
class _MyHomePageState extends State<MyHomePage> {
final testChannel = const MethodChannel("name"); //name为通道名要保证两端通道名称相等
Future<void> test() async {
return await testChannel.invokeMethod("popMessage");//invokeMthod调用方法可以添加参数
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text("test"),
onPressed: () {
test(); //点击按钮调用windows平台方法
},
),
),
);
}
}
windows平台(vs