赞
踩
要使用Flutter,就必须iOS项目加入Flutter。
然后iOS与Flutter相互通信,在跳转多次跳转Flutter之后,发现iOS使用内存每次升50~~60M内存,这样子经过多次跳转势必会造成iOS闪退,不利于开发。
下面我们看下由iOS与Flutter相互通信的交互视频,来看下每次跳转的内存上升。
怎么能够降低这个内存使用呢?这里我们就使用FlutterEngine来保证跳转flutter的时候内存稳定在50~~60M。
首先,要先声明FlutterEngine对象:
//声明FlutterEngine对象
@property (nonatomic, strong) FlutterEngine *flutterEngin;
然后,实现FlutterEngine兑现的懒加载:
#pragma mark -- Lazy method
- (FlutterEngine *)flutterEngin {
if (nil == _flutterEngin) {
FlutterEngine *flutterEngin = [[FlutterEngine alloc] initWithName:@"flutter_native" project:nil];
[flutterEngin runWithEntrypoint:nil];
[GeneratedPluginRegistrant registerWithRegistry:flutterEngin];
_flutterEngin = flutterEngin;
}
return _flutterEngin;
}
接下来,声明一个btn,通过这个btn使用FlutterEngine跳转进Flutter页面,只要使用了FlutterEngine来进行跳转,不管跳转多少次,内存都只会增长一次。
要使用FlutterEngine就需要在声明FlutterViewController的时候使用FlutterEngine,然后再声明FlutterMethodChannel和FlutterEventChannel来实现原生和flutter的双向通信,详细代码如下:
/** 使用FlutterEngine跳转Flutter */ - (IBAction)use_flutter_engin_btn_click:(id)sender { FlutterViewController *flvc = [[FlutterViewController alloc] initWithEngine:self.flutterEngin nibName:nil bundle:nil]; //单项通信管道,Flutter向原生发送消息 FlutterMethodChannel *messageChannel = [FlutterMethodChannel methodChannelWithName:@"com.flutterToNative" binaryMessenger:flvc]; __weak typeof(self) weakSelf = self; [messageChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) { if ([@"backToNative" isEqualToString:call.method]) { [weakSelf dismissViewControllerAnimated:true completion:nil]; } }]; //单项通信管道,原生向Flutter发送消息 FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"com.nativeToFlutter" binaryMessenger:flvc]; [eventChannel setStreamHandler:self]; [self presentViewController:flvc animated:true completion:nil]; } #pragma mark -- FlutterStreamHandler代理 - (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)events { if (events) { self.eventSink = events; self.eventSink(@"从原生传递过来的消息。。。。。。。"); } return nil; } // 不再需要向Flutter传递消息 - (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments { return nil; } #pragma mark -- Lazy method - (FlutterEngine *)flutterEngin { if (nil == _flutterEngin) { FlutterEngine *flutterEngin = [[FlutterEngine alloc] initWithName:@"flutter_native" project:nil]; [flutterEngin runWithEntrypoint:nil]; [GeneratedPluginRegistrant registerWithRegistry:flutterEngin]; _flutterEngin = flutterEngin; } return _flutterEngin; }
最后看一下运行起来的效果:
从运行结果可以看出,运行内存在第一次跳转到flutter页面升高之后,后续就相对于稳定。
至于为什么在跳转flutter的时候内存会猛的增高,这是因为FlutterEngine对象在跳转完Flutter再回到iOS的时候,FlutterEngine没有释放掉,是google关于Flutter对iOS支持的一个bug,希望后续这个问题会在存在。
到这里就实现了单引擎使用FlutterEngine来稳定内存的实现,后续各位在实现的时候,可以把FlutterEngine声明在AppDelegate.h文件中,或者专门声明一个FlutterManager的单利来实现整个iOS系统内只有一份FlutterEngine。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。