1.创建FlutterEngine
@interface ViewController ()
@property(nonatomic, strong) FlutterEngine* flutterEngine;
@end
// 懒加载 flutterEngine
-(FlutterEngine *)flutterEngine
{
if (!_flutterEngine) {
FlutterEngine * engine = [[FlutterEngine alloc] initWithName:@"zty"];
if (engine.run) {
_flutterEngine = engine;
}
}
return _flutterEngine;
}
2.创建FlutterViewController
self.flutterVc = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
self.flutterVc.modalPresentationStyle = UIModalPresentationFullScreen;// 设置FlutterViewController 呈现的样式
//弹出页面
[self presentViewController:self.flutterVc animated:YES completion:nil];
3.Flutter与iOS双向交互
iOS 代码,
创建FlutterMethodChannel
invokeMethod方法(发送消息)
setMethodCallHandler监听接收消息
- (IBAction)pushFlutterTwo:(id)sender {
self.flutterVc.modalPresentationStyle = UIModalPresentationFullScreen;
//创建channel
FlutterMethodChannel * methodChannel = [FlutterMethodChannel methodChannelWithName:@"two_page" binaryMessenger:self.flutterVc.binaryMessenger];
//告诉Flutter对应的页面
[methodChannel invokeMethod:@"two" arguments:nil];
//弹出页面
[self presentViewController:self.flutterVc animated:YES completion:nil];
//监听退出
[methodChannel setMethodCallHandler:^(FlutterMethodCall *_Nonnullcall, FlutterResult _Nonnull result) {
//如果是exit我就退出页面!
if ([call.method isEqualToString:@"exit"]) {
[self.flutterVc dismissViewControllerAnimated:YES completion:nil];
}
}];
}
flutter代码
创建FlutterMethodChannel
final MethodChannel _twoChannel = const MethodChannel('two_page');
setMethodCallHandler监听接收消息
_twoChannel.setMethodCallHandler((call) {
pageIndex = call.method;
print(call.method);
setState(() {});
return Future(() {});
});
invokeMethod方法(发送消息)
_twoChannel.invokeMapMethod('exit');
4.FlutterBasicMessageChannel
FlutterBasicMessageChannel,Flutter与iOS双向持续交互(flutter的TextField传值)
iOS 代码
创建FlutterBasicMessageChannel
self.msgChannel = [FlutterBasicMessageChannel messageChannelWithName:@"messageChannel" binaryMessenger:self.flutterVc.binaryMessenger];
监听收到消息
[self.msgChannel setMessageHandler:^(id _Nullablemessage, FlutterReply _Nonnull callback) {
NSLog(@"收到Flutter的:%@",message);
}];
发送消息
[self.msgChannel sendMessage:@“FlutterBasicMessageChannel”];
flutter代码
创建BasicMessageChannel
final BasicMessageChannel _messageChannel = const BasicMessageChannel('messageChannel', StandardMessageCodec());
监听收到消息
_messageChannel.setMessageHandler((message) {
print('收到来自iOS的$message');
return Future(() {});
});
发送消息
_messageChannel.send(@“hello”);