因爲flutter一直存在內存泄漏的問題,致使不少開發者不勝困擾,博主在0.9.4就開始對其代碼內部內存問題在engine層面修改代碼,獲得解決,可是對於每一個版本都須要跟隨官方打包,對於開發者並非很友好。android
然而喜出望外的是,在後來的幾個版本中,官方內置開發了手動釋放內存的方式😸ios
/**
* Destroy running context for an engine.
*
* This method can be used to force the FlutterEngine object to release all resources.
* After sending this message, the object will be in an unusable state until it is deallocated.
* Accessing properties or sending messages to it will result in undefined behavior or runtime
* errors.
*/
- (void)destroyContext;
複製代碼
翻譯以下:c++
銷燬引擎的運行上下文。 此方法可用於強制FlutterEngine對象釋放全部資源。 發送此消息後,對象將處於不可用狀態,直到解除分配爲止。 訪問屬性或向其發送消息將致使未定義的行爲或運行時錯誤。git
可是
,可是
,可是
,(重要的事說三遍) 在Flutter engine開發羣裏面,有羣友反饋還有不少問題github
沒法徹底釋放內存算法
偶現崩潰json
官方回覆,慎用 github.com/flutter/flu…bash
偶現崩潰的是什麼鬼,暫時沒有遇到,很差說。 以前博主遇到的崩潰是本身使用方式的問題,在fluttervc關閉以後還有任務在執行methodchannel,即還在調用plugin,這個能夠在開發上避免。 值得注意的是,flutter中使用c++實現,本身對於內存管理並非很好app
內存問題自測以下dom
確實存在問題,還有將近30M沒有被釋放,查看一下當前內存對象,以下圖
一個一個看還有那些沒有被釋放吧
Least Recently Used 近期最少使用算法。 內存管理的一種頁面置換算法,對於在內存中但又不用的數據塊(內存塊)叫作LRU,flutter engine 會根據哪些數據屬於LRU而將其移出內存而騰出空間來加載另外的數據。
BackgroundCompiler 在後臺線程中運行優化編譯的類。 實現:每一個隔離一個任務,它與擁有isolate一塊兒消失,後臺編譯器中沒有OSR編譯。
vm和開發平臺通訊的機制,好比jit即時編譯的dill文件,經過socket傳遞給dart vm,vm經過rpc加載文件,重置線程,從而實現hotreload熱重載
定義在dart vm,service.cc中,都繼承自MethodParameter,作對應參數校驗,參數解析用。編譯dart文件用的
在dart 運行時負責操做系統線程,建立線程,移除線程,線程查找與管理。 以下圖
![]()
FlutterEngineRegistrar 註冊使用key註冊plugin的地方,全部plugin調用dart底層的方法都會經過 handlemethodcall 回調給使用者, 其初始化的地方是引發內存泄漏的地方
- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_pluginKey = pluginKey;// [pluginKey retain];
_flutterEngine = flutterEngine;// [flutterEngine retain];
return self;
}
複製代碼
此處有一篇文章介紹,解決engine的循環引用 文章
FlutterStringCodec string編解碼 FlutterJsonMessageCodec json編解碼
不看不知道,一看嚇一跳,也居然是個單例,固然不會被釋放了,也能理解,在flutter中用到jsonmssage的地方不少,用不着每次都初始化
![]()
代碼實現的地方
@implementation FlutterJSONMessageCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterJSONMessageCodec new];
}
return _sharedInstance;
}
複製代碼
指針獲取 flutter isolate service dartvm symbolmapping
~~ 文章完 ~~
若是你想深刻討論flutter的問題,歡迎加入咱們的QQ羣 217429001
完整測試代碼以下
#import "FlutterTesterViewController.h"
#import <Flutter/Flutter.h>
#import "GeneratedPluginRegistrant.h"
@interface FlutterTesterViewController ()
@property (nonatomic, weak) FlutterViewController * ctr;
@property (nonatomic, weak) FlutterEngine * engine;
@end
@implementation FlutterTesterViewController
- (void)viewDidLoad {
[super viewDidLoad];
float Y = 210;
[self createButton:@"加載boundle資源" frame:CGRectMake(80.0, Y, 160.0, 40.0) action:@selector(handleBoundleResource )];
Y += 40.0 + 10;
[self createButton:@"autorelease" frame:CGRectMake(80.0, Y, 160.0, 40.0) action:@selector(handleAutoRelase)];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"flutter_assets"] ;
NSLog(@"path: %@",path);
}
-(void)handleNetWorkResource:(UIButton *)button{
}
/**
* 加載boundle資源
*/
- (void)handleBoundleResource {
FlutterDartProject * dart = [[FlutterDartProject alloc] init];
FlutterEngine * engine = [[FlutterEngine alloc] initWithName:@"ios.dart.flutter"
project:dart];
[engine runWithEntrypoint:nil];
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil];
[GeneratedPluginRegistrant registerWithRegistry:flutterViewController];
[self addBackButton:flutterViewController];
[flutterViewController setInitialRoute:@"route1"];
[self presentViewController:flutterViewController animated:YES completion:nil];
self.engine = engine;
}
-(void)handleAutoRelase{
FlutterBasicMessageChannel* channel;
FlutterEngine * engine;
@autoreleasepool {
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] init];
channel = flutterViewController.engine.systemChannel;
engine = flutterViewController.engine;
NSLog(@"engine111:%@",engine);
}
NSLog(@"engine222:%@",engine);
[channel sendMessage:@"Hello!"];
[channel setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { }];
}
-(void)addBackButton:(UIViewController *)flutterViewController{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@"關閉" forState:UIControlStateNormal];
btn.frame = CGRectMake(10, 100, 50, 30);
[btn addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
[flutterViewController.view addSubview:btn];
self.ctr = flutterViewController;
});
}
-(void)buttonTap:(id)sender{
// [self.navigationController popViewControllerAnimated:YES];
__weak __typeof(self)weakSelf = self;
[self.ctr dismissViewControllerAnimated:YES completion:^{
[weakSelf.engine destroyContext];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(UIButton *)createButton:(NSString *)title frame:(CGRect)frame action:(SEL)selector{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:selector
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title forState:UIControlStateNormal];
UIColor * bgcolor = [UIColor colorWithRed:arc4random()%256/255. green:arc4random()%256/255. blue:arc4random()%256/255. alpha:1];
[button setBackgroundColor:bgcolor];
button.frame = frame;
[self.view addSubview:button];
return button;
}
@end
複製代碼