qt框架的开发模式_Flutter 混合开发框架模式探索
Flutter 混合開發(fā)框架模式探索
由于 Google 官方提供的 Flutter 混合式開發(fā)方案過于簡單,僅支持打開一個 Flutter View 的能力,而不支持路由間傳參、統(tǒng)一的生命周期、路由棧管理等業(yè)務(wù)開發(fā)中必要的能力,因此我們需要借助第三方混合開發(fā)框架(如 Flutter Boost、Thrio、QFlutter 等)的整合能力才能將 Flutter 混合開發(fā)模式投入與生產(chǎn)環(huán)境。本文中,我們來研究一下這類混合開發(fā)框架的職能、架構(gòu)與源碼。
1. 核心職能與框架目標(biāo)
一個合格的混合開發(fā)框架至少需要支持到以下能力:
對于以上幾點目標(biāo),我們以 iOS 為例,來逐步挖掘 Flutter 混合開發(fā)模式的最佳實現(xiàn)。
注:因為篇幅問題,本文不探究 Android 的實現(xiàn),從 iOS 切入只是分析問題的一個角度,因 Android 與 iOS 的實現(xiàn)原理一致,具體實現(xiàn)則大同小異。其次因 Channel 通信層代碼實現(xiàn)比較繁雜,此文對于 Channel 通信層的講解僅停留在使用層面上,具體實現(xiàn)讀者可以自行研究。注:本文的 Flutter Boost 版本為 1.12.13,Thrio 的版本為 0.1.0
2. 從 FlutterViewController 開始
在混合開發(fā)中,我們使用 Flutter 作為插件化開發(fā),需要起一個 FlutterViewController,這是一個 UIViewController 的實現(xiàn),其依附于 FlutterEngine,給 Flutter 傳遞 UIKit 的輸入事件,并展示被 FlutterEngine 渲染的每一幀 Flutter views。而這個 FlutterEngine 則充當(dāng) Dart VM 和 Flutter 運行時的環(huán)境。
需要注意的是,一個 Flutter Engine 只能最多同時運行一個 FlutterViewController。
FlutterEngine: The FlutterEngine class coordinates a single instance of execution for a FlutterDartProject. It may have zero or one FlutterViewController at a time.啟動 Engine:
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"]; [self.flutterEngine run];創(chuàng)建 FlutterViewController 并展示
FlutterViewController *flutterViewController =[[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil]; [self presentViewController:flutterViewController animated:YES completion:nil];創(chuàng)建一個 FlutterViewController 我們既可以用已經(jīng)運行中的 FlutterEngine 去初始化,也可以創(chuàng)建的時候同時去隱式啟動一個 FlutterEngine(不過不建議這樣做,因為按需創(chuàng)建 FlutterEngine 的話,在 FlutterViewController 被 present 出來之后,第一幀圖像渲染完之前,將會引入明顯的延遲),這里我們用前者的方式去創(chuàng)建。
FlutterEngine: https://api.flutter.dev/objcdoc/Classes/FlutterEngine.htmlFlutterViewController: https://api.flutter.dev/objcdoc/Classes/FlutterViewController.html
至此,我們通過官方提供的方案在 Native 工程中啟動 Flutter Engine 并通過 FlutterViewController 展示 Flutter 頁面。
在 Flutter 頁面中,我們可以使用 Navigator.push 在打開另一個 Flutter 頁面(Route):
因此對于這種路由棧我們很容易實現(xiàn):
即整個 Flutter 運行在一個單例的 FlutterViewController 容器里,Flutter 內(nèi)部的所有頁面都在這個容器中管理。但如果要實現(xiàn)下面這種 Native 與 Flutter 混合跳轉(zhuǎn)的這種混合路由棧,我們要如何實現(xiàn)呢?
最基本的解決思路是,把這個 FlutterViewController 與 NativeViewController 混合起來,直接讓 FlutterViewController 在 iOS 的路由棧中來回移動,如下圖所示:
這種方案相對復(fù)雜,回到我們上面混合棧的場景,這需要精準(zhǔn)記錄每個 Flutter 頁面和 Native 容器所處的位置,得知道自己 pop 之后應(yīng)該回到上一層 Flutter 頁面,還是切換另一個 NativeViewController,這就得維護(hù)好頁面索引,并改造原生的pop 時間與 Navigator.pop 事件,使兩者統(tǒng)一起來。
我們來看看業(yè)界的一些解決方案吧!
3. Flutter Boost
對于混合棧問題,Flutter Boost 會將每個 Flutter 頁面用 FlutterViewController 包裝起來,使之成為多例,用起來就如同 Webview 一樣:
Flutter Boost 的源碼之前在另一篇文章中梳理過《Flutter Boost 混合開發(fā)實踐與源碼解析(以 Android 為例)》,那篇文章中梳理了一下 Android 側(cè)打開頁面流程的源碼,本文中則盡量不重復(fù)介紹源碼,并且將以 iOS 側(cè)來重點梳理一下 Flutter Boost 究竟是如何實現(xiàn)的。
3.1 從 Native 打開頁面
本節(jié)分析 Flutter Boost 如何從 Native 打開頁面嗎,即包含以下兩種情況:
在工程中,我們需要接入以下代碼集成 Flutter Boost:
// AppDelegate.m- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {PlatformRouterImp *router = [PlatformRouterImp new];[FlutterBoostPlugin.sharedInstance startFlutterWithPlatform:routeronStart:^(FlutterEngine *engine) {}];self.window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];[self.window makeKeyAndVisible];UINavigationController *rvc = [[UINavigationController alloc] initWithRootViewController:tabVC];router.navigationController = rvc;self.window.rootViewController = rvc;return YES; }// PlatformRouterImp.m- (void)openNativeVC:(NSString *)nameurlParams:(NSDictionary *)paramsexts:(NSDictionary *)exts{UIViewController *vc = UIViewControllerDemo.new;BOOL animated = [exts[@"animated"] boolValue];if([params[@"present"] boolValue]){[self.navigationController presentViewController:vc animated:animated completion:^{}];}else{[self.navigationController pushViewController:vc animated:animated];} }- (void)open:(NSString *)nameurlParams:(NSDictionary *)paramsexts:(NSDictionary *)extscompletion:(void (^)(BOOL))completion {if ([name isEqualToString:@"native"]) { // 模擬打開native頁面[self openNativeVC:name urlParams:params exts:exts];return;}BOOL animated = [exts[@"animated"] boolValue];FLBFlutterViewContainer *vc = FLBFlutterViewContainer.new;[vc setName:name params:params];[self.navigationController pushViewController:vc animated:animated];if(completion) completion(YES); }可以發(fā)現(xiàn),我們在工程中首先要啟動引擎,對應(yīng)的 Flutter Boost 源碼如下:
// FlutterBoostPlugin.m - (void)startFlutterWithPlatform:(id<FLBPlatform>)platformengine:(FlutterEngine *)enginepluginRegisterred:(BOOL)registerPluginonStart:(void (^)(FlutterEngine * _Nonnull))callback{static dispatch_once_t onceToken;__weak __typeof__(self) weakSelf = self;dispatch_once(&onceToken, ^{__strong __typeof__(weakSelf) self = weakSelf;FLBFactory *factory = FLBFactory.new;self.application = [factory createApplication:platform];[self.application startFlutterWithPlatform:platformwithEngine:enginewithPluginRegisterred:registerPluginonStart:callback];}); }// FLBFlutterApplication.m- (void)startFlutterWithPlatform:(id<FLBPlatform>)platformwithEngine:(FlutterEngine* _Nullable)enginewithPluginRegisterred:(BOOL)registerPluginonStart:(void (^)(FlutterEngine *engine))callback {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{self.platform = platform;self.viewProvider = [[FLBFlutterEngine alloc] initWithPlatform:platform engine:engine];self.isRunning = YES;if(registerPlugin){Class clazz = NSClassFromString(@"GeneratedPluginRegistrant");FlutterEngine *myengine = [self.viewProvider engine];if (clazz && myengine) {if ([clazz respondsToSelector:NSSelectorFromString(@"registerWithRegistry:")]) {[clazz performSelector:NSSelectorFromString(@"registerWithRegistry:")withObject:myengine];}}}if(callback) callback(self.viewProvider.engine);}); }可以發(fā)現(xiàn)啟動引擎時 startFlutterWithPlatform 需要傳入路由管理類,而在 FLBPlatform.h 中可以看到 open 接口是由業(yè)務(wù)側(cè) Native 傳過來的實現(xiàn)。
// PlatformRouterImp.m- (void)open:(NSString *)nameurlParams:(NSDictionary *)paramsexts:(NSDictionary *)extscompletion:(void (^)(BOOL))completion {if ([name isEqualToString:@"native"]) { // 模擬打開native頁面[self openNativeVC:name urlParams:params exts:exts];return;}BOOL animated = [exts[@"animated"] boolValue];FLBFlutterViewContainer *vc = FLBFlutterViewContainer.new;[vc setName:name params:params];[self.navigationController pushViewController:vc animated:animated];if(completion) completion(YES); }之后要在業(yè)務(wù)側(cè) AppDelegate.m 中初始化一個 UINavigationController,之后在路由管理類中實現(xiàn) open 方法,即在這個 navigationContainer 中 push 一個 FLBFlutterViewContainer 容器,它的父類其實就是我們第一章節(jié)所說的 FlutterViewController。核心流程的代碼如下:
// FLBFlutterViewContainer.m- (instancetype)init {[FLUTTER_APP.flutterProvider prepareEngineIfNeeded];if(self = [super initWithEngine:FLUTTER_APP.flutterProvider.enginenibName:_flbNibNamebundle:_flbNibBundle]){self.modalPresentationStyle = UIModalPresentationFullScreen;[self _setup];}return self; }沒錯,它調(diào)用的便是我們第一章節(jié)所說的,通過 initWithEngine 來創(chuàng)建 FlutterViewController。
那 Native 頁面如何打開 Flutter 頁面?業(yè)務(wù)側(cè)調(diào)用 FlutterBoostPlugin 的 open 方法:
- (IBAction)pushFlutterPage:(id)sender {[FlutterBoostPlugin open:@"first" urlParams:@{kPageCallBackId:@"MycallbackId#1"} exts:@{@"animated":@(YES)} onPageFinished:^(NSDictionary *result) {NSLog(@"call me when page finished, and your result is:%@", result);} completion:^(BOOL f) {NSLog(@"page is opened");}]; }Flutter Boost 對應(yīng)的處理如下:
// FlutterBoostPlugin.m + (void)open:(NSString *)url urlParams:(NSDictionary *)urlParams exts:(NSDictionary *)exts onPageFinished:(void (^)(NSDictionary *))resultCallback completion:(void (^)(BOOL))completion{id<FLBFlutterApplicationInterface> app = [[FlutterBoostPlugin sharedInstance] application];[app open:url urlParams:urlParams exts:exts onPageFinished:resultCallback completion:completion]; }// FLBFlutterApplication.m - (void)open:(NSString *)urlurlParams:(NSDictionary *)urlParamsexts:(NSDictionary *)extsonPageFinished:(void (^)(NSDictionary *))resultCallbackcompletion:(void (^)(BOOL))completion {NSString *cid = urlParams[kPageCallBackId];if(!cid){static int64_t sCallbackID = 1;cid = @(sCallbackID).stringValue;sCallbackID += 2;NSMutableDictionary *newParams = [[NSMutableDictionary alloc]initWithDictionary:urlParams];[newParams setObject:cid?cid:@"__default#0__" forKey:kPageCallBackId];urlParams = newParams;}_previousViewController = [self flutterViewController];_callbackCache[cid] = resultCallback;if([urlParams[@"present"]respondsToSelector:@selector(boolValue)] && [urlParams[@"present"] boolValue] && [self.platform respondsToSelector:@selector(present:urlParams:exts:completion:)]){[self.platform present:urlurlParams:urlParamsexts:extscompletion:completion];}else{[self.platform open:urlurlParams:urlParamsexts:extscompletion:completion];} }而 Platform 的 open 就是業(yè)務(wù)側(cè)傳過來的路由類中實現(xiàn)的 open,之后就走到了我們本章開頭分析的部分,前文分析過了,后文也有總結(jié),這里不再贅述了。
小結(jié)一下,Native 無論打開 Native 還是 Flutter,都需要業(yè)務(wù)側(cè)調(diào)用 Flutter Boost 的 open 方法,而 Flutter Boost 的 open 方法的實現(xiàn)最后其實還是回到了業(yè)務(wù)側(cè)路由管理類中實現(xiàn)的 open 方法,那么:
3.2 從 Flutter 打開頁面
本節(jié)分析 Flutter Boost 如何從 Native 打開頁面嗎,即包含以下兩種情況:
Dart 業(yè)務(wù)側(cè)直接調(diào)用 open 方法打開 Native 或者 Flutter 頁面:
FlutterBoost.singleton.open("native").then((Map value) {print("call me when page is finished. did recieve native route result $value"); });FlutterBoost.singleton.open("flutterPage").then((Map value) {print("call me when page is finished. did recieve native route result $value"); });open 的源碼如下,可見它的核心是使用 MethodChannel 向 Native 側(cè)發(fā)送 openPage 消息:
// flutter_boost.dart Future<Map<dynamic, dynamic>> open(String url,{Map<dynamic, dynamic> urlParams, Map<dynamic, dynamic> exts}) {Map<dynamic, dynamic> properties = new Map<dynamic, dynamic>();properties["url"] = url;properties["urlParams"] = urlParams;properties["exts"] = exts;return channel.invokeMethod<Map<dynamic, dynamic>>('openPage', properties); }// boost_channel.dart final MethodChannel _methodChannel = MethodChannel("flutter_boost");Future<T> invokeMethod<T>(String method, [dynamic arguments]) async {assert(method != "__event__");return _methodChannel.invokeMethod<T>(method, arguments); }iOS 側(cè)監(jiān)聽 Dart 側(cè)來的消息,針對 openPage 做處理,核心是調(diào)用 FLBFlutterApplication 中的 open 方法:
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {if([@"openPage" isEqualToString:call.method]){NSDictionary *args = [FLBCollectionHelper deepCopyNSDictionary:call.argumentsfilter:^bool(id _Nonnull value) { return ![value isKindOfClass:NSNull.class];}];NSString *url = args[@"url"];NSDictionary *urlParams = args[@"urlParams"];NSDictionary *exts = args[@"exts"];NSNull2Nil(url);NSNull2Nil(urlParams);NSNull2Nil(exts);[[FlutterBoostPlugin sharedInstance].application open:urlurlParams:urlParamsexts:extsonPageFinished:resultcompletion:^(BOOL r) {}];} }// FLBFlutterApplication.m- (FlutterViewController *)flutterViewController {return self.flutterProvider.engine.viewController; }- (void)open:(NSString *)urlurlParams:(NSDictionary *)urlParamsexts:(NSDictionary *)extsonPageFinished:(void (^)(NSDictionary *))resultCallbackcompletion:(void (^)(BOOL))completion {NSString *cid = urlParams[kPageCallBackId];if(!cid){static int64_t sCallbackID = 1;cid = @(sCallbackID).stringValue;sCallbackID += 2;NSMutableDictionary *newParams = [[NSMutableDictionary alloc]initWithDictionary:urlParams];[newParams setObject:cid?cid:@"__default#0__" forKey:kPageCallBackId];urlParams = newParams;}_previousViewController = [self flutterViewController];_callbackCache[cid] = resultCallback;if([urlParams[@"present"]respondsToSelector:@selector(boolValue)] && [urlParams[@"present"] boolValue] && [self.platform respondsToSelector:@selector(present:urlParams:exts:completion:)]){[self.platform present:urlurlParams:urlParamsexts:extscompletion:completion];}else{[self.platform open:urlurlParams:urlParamsexts:extscompletion:completion];} }同前文分析的一樣,監(jiān)聽到這個 openPage 之后會調(diào)用 Flutter Boost 的 open 方法,而它最后還是會走到 Native 業(yè)務(wù)側(cè)傳來的路由管理類中實現(xiàn)的 open 方法,也是就說從 Flutter 打開頁面,最終也是交由 Native 去負(fù)責(zé) push。
小結(jié)一下,Flutter 無論的打開 Flutter 還是 Native 頁面,都需要給 iOS 側(cè)發(fā)送 openPage 的消息,iOS 側(cè)收到消息后會執(zhí)行 Flutter Boost 的 open 方法,而它的實現(xiàn)就是業(yè)務(wù)側(cè)的路由管理類中的open 方法,即最終仍然交由業(yè)務(wù)側(cè)的路由去實現(xiàn)。
3.3 Flutter 容器切換
我們前文說到路由管理統(tǒng)一收歸給 Native 側(cè)去實現(xiàn),每 push 一個 page (無論 Flutter 還是 Native)都是 push 一個容器。統(tǒng)一收歸的好處是由 Native 業(yè)務(wù)側(cè)控制,使用起來直接、簡單;每次 push 一個容器的好處是直觀、簡單。
但是我們之前說到 Flutter Engine 只能最多同時掛載一個 FlutterViewController,那每次打開 Flutter Page 的時候都會生成一個 vc 會導(dǎo)致問題嗎?我們來看看 Flutter Boost 是如何處理的:
// FLBFlutterViewContainer.m - (void)viewWillAppear:(BOOL)animated {//For new page we should attach flutter view in view will appear[self attatchFlutterEngine];[BoostMessageChannel willShowPageContainer:^(NSNumber *result) {}pageName:_nameparams:_paramsuniqueId:self.uniqueIDString];//Save some first time page info.[FlutterBoostPlugin sharedInstance].fPagename = _name;[FlutterBoostPlugin sharedInstance].fPageId = self.uniqueIDString;[FlutterBoostPlugin sharedInstance].fParams = _params;[super bridge_viewWillAppear:animated];[self.view setNeedsLayout]; }- (void)attatchFlutterEngine {[FLUTTER_APP.flutterProvider atacheToViewController:self]; }可以看到在容器 willAppear 的時候會調(diào)用 attatchFlutterEngine 方法,其用于切換 engine 的 viewController。即,每次打開 Flutter Page 的時候,剛生成的承載它的容器 FlutterViewController 都會被掛載在 engine 上。是的,Flutter Boost 是通過不斷切換 engine 的 viewController 來展示 Flutter 容器和頁面的。
// FLBFlutterEngine.m - (BOOL)atacheToViewController:(FlutterViewController *)vc {if(_engine.viewController != vc){_engine.viewController = vc;return YES;}return NO; }3.4 統(tǒng)一生命周期與路由事件通知
那 Flutter Boost 是如何解決 Native 與 Dart 頁面生命周期不一致的問題呢?
我們還是以 2.4 中 FLBFlutterViewController viewWillAppear 來舉例吧,可以看到在這個函數(shù)中會執(zhí)行 willShowPageContainer,它的實現(xiàn)在 BoostMessageChannel.m 中。
// BoostMessageChannel.m+ (void)willShowPageContainer:(void (^)(NSNumber *))result pageName:(NSString *)pageName params:(NSDictionary *)params uniqueId:(NSString *)uniqueId{if ([pageName isEqualToString:kIgnoreMessageWithName]) {return;}NSMutableDictionary *tmp = [NSMutableDictionary dictionary];if(pageName) tmp[@"pageName"] = pageName;if(params) tmp[@"params"] = params;if(uniqueId) tmp[@"uniqueId"] = uniqueId;[self.methodChannel invokeMethod:@"willShowPageContainer" arguments:tmp result:^(id tTesult) {if (result) {result(tTesult);}}];}它只做了一件事情,就是通過 methodChannel 向 Dart 側(cè)發(fā)送 willShowPageContainer 這個消息。Dart 側(cè)在 container_coordinator.dart 中接受消息:
Flutter Boost 的 Dart 側(cè)代碼比較簡單,container_coordinator.dart 顧名思義,就是協(xié)同 Native 側(cè)容器的類,它負(fù)責(zé)監(jiān)聽 Native 來的消息,并使用 container_manager.dart 容器管理類來進(jìn)行一些處理。// container_coordinator.dartFuture<dynamic> _onMethodCall(MethodCall call) {Logger.log("onMetohdCall ${call.method}");switch (call.method) {case "willShowPageContainer":{String pageName = call.arguments["pageName"];Map params = call.arguments["params"];String uniqueId = call.arguments["uniqueId"];_nativeContainerWillShow(pageName, params, uniqueId);}break;} }bool _nativeContainerWillShow(String name, Map params, String pageId) {if (FlutterBoost.containerManager?.containsContainer(pageId) != true) {FlutterBoost.containerManager?.pushContainer(_createContainerSettings(name, params, pageId));}// ...省略一些優(yōu)化代碼return true; }核心是執(zhí)行 FlutterBoost.containerManager?.pushContainer,它在 container_manager.dart 容器管理類中實現(xiàn):
// container_manager.dartfinal List<BoostContainer> _offstage = <BoostContainer>[]; BoostContainer _onstage; enum ContainerOperation { Push, Onstage, Pop, Remove }void pushContainer(BoostContainerSettings settings) {assert(settings.uniqueId != _onstage.settings.uniqueId);assert(_offstage.every((BoostContainer container) =>container.settings.uniqueId != settings.uniqueId));_offstage.add(_onstage);_onstage = BoostContainer.obtain(widget.initNavigator, settings);setState(() {});for (BoostContainerObserver observer in FlutterBoost.singleton.observersHolder.observersOf<BoostContainerObserver>()) {observer(ContainerOperation.Push, _onstage.settings);}Logger.log('ContainerObserver#2 didPush'); }在執(zhí)行 BoostContainer.obtain 的過程中,內(nèi)部會出發(fā)生命周期的監(jiān)聽。除此之外還執(zhí)行了 observer(ContainerOperation.Push, _onstage.settings); ,以此來觸發(fā) Push 事件的通知。
其實在 FlutterBoost 中,框架一共注冊了 3 種類型的事件監(jiān)聽:
它們都伴隨著混合路由棧的跳轉(zhuǎn)來觸發(fā)相關(guān)的事件,至于通信層的源碼本文不再研究,留給有興趣的同學(xué)自己看看。
下圖是本章 Flutter Boost 打開頁面的流程總結(jié):
注:此方案頻繁地去創(chuàng)建 FlutterViewController,在 pop 某些 FlutterViewController 之后,這些內(nèi)存并沒有被 engine 釋放,造成內(nèi)存泄露:https://github.com/flutter/flutter/issues/25255,這是 engine 的 bug,貌似至今仍未得到很好的解決。4. Thrio
Thrio 是上個月(2020.03) Hellobike 開源的又一款 Flutter 混合棧框架,這個框架處理的核心問題也依然是我們在第一章拋出來的兩個點:
在本文中,我們主要來看看 Thrio 是如何實現(xiàn)混合棧管理的,至于通信層的邏輯,我們依然只是順帶講解一些,具體實現(xiàn)比較繁雜因此本文不再分析其源碼。
我們可以先看一下時序圖來宏觀上有一個流程的了解:
4.1 調(diào)用
4.1.1 從 Native 打開頁面
從 iOS 業(yè)務(wù)側(cè)調(diào)用 openUrl 即可打開 Native 或 Flutte 頁面:
- (IBAction)pushNativePage:(id)sender {[ThrioNavigator pushUrl:@"native1"]; }- (IBAction)pushFlutterPage:(id)sender {[ThrioNavigator pushUrl:@"biz1/flutter1"]; }openUrl 最終會調(diào)用 thrio_pushUrl:
// ThrioNavigator.m + (void)_pushUrl:(NSString *)urlparams:(id _Nullable)paramsanimated:(BOOL)animatedresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {[self.navigationController thrio_pushUrl:urlparams:paramsanimated:animatedfromEntrypoint:nilresult:^(NSNumber *idx) {if (result) {result(idx);}} poppedResult:poppedResult]; }4.1.2 從 Flutter 打開頁面
那我們轉(zhuǎn)過頭來看看,Thrio 究竟如何實現(xiàn)從 Dart 業(yè)務(wù)側(cè)打開頁面的:
InkWell(onTap: () => ThrioNavigator.push(url: 'biz1/flutter1',params: {'1': {'2': '3'}},poppedResult: (params) =>ThrioLogger.v('biz1/flutter1 popped:$params'),),child: Container(padding: const EdgeInsets.all(8),margin: const EdgeInsets.all(8),color: Colors.yellow,child: Text('push flutter1',style: TextStyle(fontSize: 22, color: Colors.black),)), ),Thrio 處理的處理如下,它會向 Native 側(cè)通過 MethodChannel 發(fā)一條 push 消息:
// thrio_navigator.dart static Future<int> push({@required String url,params,bool animated = true,NavigatorParamsCallback poppedResult,}) =>ThrioNavigatorImplement.push(url: url,params: params,animated: animated,poppedResult: poppedResult,);// thrio_navigator_implement.dart static Future<int> push({@required String url,params,bool animated = true,NavigatorParamsCallback poppedResult,}) {if (_default == null) {throw ThrioException('Must call the `builder` method first');}return _default._sendChannel.push(url: url, params: params, animated: animated).then<int>((index) {if (poppedResult != null && index != null && index > 0) {_default._pagePoppedResults['$url.$index'] = poppedResult;}return index;});}// navigator_route_send_channel.dart Future<int> push({@required String url,params,bool animated = true,}) {final arguments = <String, dynamic>{'url': url,'animated': animated,'params': params,};return _channel.invokeMethod<int>('push', arguments);}Native 側(cè)接受到 push 消息后,同樣會調(diào)用 thrio_pushUrl,即,從 Native 或 Flutter 打開頁面的邏輯,都統(tǒng)一收歸到 Native 側(cè)進(jìn)行處理了:
- (void)_onPush {__weak typeof(self) weakself = self;[_channel registryMethodCall:@"push"handler:^void(NSDictionary<NSString *,id> * arguments,ThrioIdCallback _Nullable result) {NSString *url = arguments[@"url"];if (url.length < 1) {if (result) {result(nil);}return;}id params = [arguments[@"params"] isKindOfClass:NSNull.class] ? nil : arguments[@"params"];BOOL animated = [arguments[@"animated"] boolValue];ThrioLogV(@"on push: %@", url);__strong typeof(weakself) strongSelf = weakself;[ThrioNavigator.navigationController thrio_pushUrl:urlparams:paramsanimated:animatedfromEntrypoint:strongSelf.channel.entrypointresult:^(NSNumber *idx) { result(idx); }poppedResult:nil];}]; }4.1.3 thrio_pushUrl
那我們看看這個 thrio_pushUrl 究竟做了什么事情:
// UINavigationController+Navigator.m - (void)thrio_pushUrl:(NSString *)urlparams:(id _Nullable)paramsanimated:(BOOL)animatedfromEntrypoint:(NSString * _Nullable)entrypointresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {@synchronized (self) {UIViewController *viewController = [self thrio_createNativeViewControllerWithUrl:url params:params];if (viewController) {// 4.2 中分析} else {// 4.3 中分析}} }可以發(fā)現(xiàn)它做的第一件事情就是調(diào)用 thrio_createNativeViewControllerWithUrl 創(chuàng)建一個 viewController,thrio_createNativeViewControllerWithUrl 實現(xiàn)如下:
- (UIViewController * _Nullable)thrio_createNativeViewControllerWithUrl:(NSString *)url params:(NSDictionary *)params {UIViewController *viewController;NavigatorPageBuilder builder = [ThrioNavigator pageBuilders][url];if (builder) {viewController = builder(params);// 省略一些額外處理的代碼}return viewController; }理解這段代碼要結(jié)合 Thrio 的路由注冊流程,Native 業(yè)務(wù)側(cè)注冊了路由之后,Thrio 中會維護(hù)一個 map 來管理這些注冊的路由,key 為注冊的路由名,value 為對應(yīng)的 builder。那么 thrio_createNativeViewControllerWithUrl 其實就是嘗試去根據(jù)路由名去創(chuàng)建一個 NativeViewController 容器,如果注冊過的就肯定會返回 viewController,若在 Native 側(cè)沒有注冊過這個路由,就返回 nil。因此也就有了下面根據(jù) viewController 存在與否走的兩套邏輯了。那么我們看看什么時候會創(chuàng)建成功呢?那就是業(yè)務(wù)側(cè) pushUrl 打開的是一個在 Native 注冊的頁面就會返回 NativeController,否則沒有注冊過去調(diào)用 pushUrl,意味著業(yè)務(wù)側(cè)打開的路由名是從 Flutter 側(cè)注冊的,那它要打開的就是一個 FlutterViewController。
Thrio 作者 @稻子 指出:這里還包含 Flutter 側(cè)也沒有注冊的邏輯,這樣寫是為了判斷路由是否在 Native 側(cè)注冊了,如果注冊了就打開原生頁面,否則就交由 Flutter 處理。如果 Flutter 側(cè)注冊了,就會打開 Flutter 頁面,否則就返回 null。這里后面也會說到,其實咱們說想要打開 Flutter 頁面,也包括了這個頁面沒有被注冊的情況了。因此:
接下來我們來繼續(xù)分析這兩段邏輯。
注:Thrio 將容器分為兩類,一類是 NativeViewController,即承載 Native 頁面的容器;另一類是 FlutterViewController,即承載 Flutter 頁面的容器。4.2 打開 Native 頁面
viewController 存在,即要打開的是 Native 頁面:
if (viewController) {[self thrio_pushViewController:viewControllerurl:urlparams:paramsanimated:animatedfromEntrypoint:entrypointresult:resultpoppedResult:poppedResult];}thrio_pushViewController 實現(xiàn)如下:
- (void)thrio_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {// ...省略處理 navigatorbar 的代碼[self thrio_pushViewController:viewController animated:animated]; }我們打開的是 NativeViewController,因此走的是下面的分支,調(diào)用 thrio_pushViewController:
- (void)thrio_pushViewController:(UIViewController *)viewControllerurl:(NSString *)urlparams:(id _Nullable)paramsanimated:(BOOL)animatedfromEntrypoint:(NSString * _Nullable)entrypointresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {if (viewController) {NSNumber *index = @([self thrio_getLastIndexByUrl:url].integerValue + 1);__weak typeof(self) weakself = self;[viewController thrio_pushUrl:urlindex:indexparams:paramsanimated:animatedfromEntrypoint:entrypointresult:^(NSNumber *idx) {if (idx && [idx boolValue]) {__strong typeof(weakself) strongSelf = weakself;[strongSelf pushViewController:viewController animated:animated];}if (result) {result(idx);}} poppedResult:poppedResult];} }這里主要做了兩件事:
其實這里就已經(jīng)打開了容器,但是我們還是要看看第一步調(diào)用 thrio_pushUrl 做了什么:
- (void)thrio_pushUrl:(NSString *)urlindex:(NSNumber *)indexparams:(id _Nullable)paramsanimated:(BOOL)animatedfromEntrypoint:(NSString * _Nullable)entrypointresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {NavigatorRouteSettings *settings = [NavigatorRouteSettings settingsWithUrl:urlindex:indexnested:self.thrio_firstRoute != nilparams:params];if (![self isKindOfClass:NavigatorFlutterViewController.class]) { // 當(dāng)前頁面為原生頁面[ThrioNavigator onCreate:settings];}NavigatorPageRoute *newRoute = [NavigatorPageRoute routeWithSettings:settings];newRoute.fromEntrypoint = entrypoint;newRoute.poppedResult = poppedResult;if (self.thrio_firstRoute) {NavigatorPageRoute *lastRoute = self.thrio_lastRoute;lastRoute.next = newRoute;newRoute.prev = lastRoute;} else {self.thrio_firstRoute = newRoute;}if ([self isKindOfClass:NavigatorFlutterViewController.class]) {// 打開 Flutter 頁面的邏輯,4.3.1 中分析} }關(guān)鍵是調(diào)用了 onCreate 函數(shù),至于剩下的業(yè)務(wù),是對頁面指針的處理,這里不做分析了。我們來看看 onCreate 做了什么事情:
- (void)onCreate:(NavigatorRouteSettings *)routeSettings {NSDictionary *arguments = [routeSettings toArguments];[_channel invokeMethod:@"__onOnCreate__" arguments:arguments]; }這里是使用 MethodChannel 向 Dart 側(cè)發(fā)送一條 onOnCreate 消息,Dart 側(cè)收到之后會交由相關(guān)的事件進(jìn)行處理:
NavigatorPageObserverChannel() {_on('onCreate',(pageObserver, routeSettings) => pageObserver.onCreate(routeSettings),); }void _on(String method, NavigatorPageObserverCallback callback) =>_channel.registryMethodCall('__on${method[0].toUpperCase() + method.substring(1)}__', ([arguments]) {final routeSettings = NavigatorRouteSettings.fromArguments(arguments);final pageObservers = ThrioNavigatorImplement.pageObservers;for (final pageObserver in pageObservers) {if (pageObserver is NavigatorPageObserverChannel) {continue;}callback(pageObserver, routeSettings);}return Future.value();});即 Thrio 在這里完成了生命周期的統(tǒng)一處理,其實現(xiàn)方式與 FlutterBoost 其實是一致,都是在混合棧跳轉(zhuǎn)的過程中順帶通知相關(guān)事件,至于通信層的具體邏輯這里也不再具體分析了。另外,Thrio Dart 側(cè)的代碼比較簡潔,推薦有興趣的同學(xué)自行閱讀。
4.3 打開 Flutter 頁面
若 viewController 不存在,即業(yè)務(wù)側(cè)要打開的是 Native 頁面:
if (viewController) {// 4.2 } else {NSString *entrypoint = @"";if (ThrioNavigator.isMultiEngineEnabled) {entrypoint = [url componentsSeparatedByString:@"/"].firstObject;}__weak typeof(self) weakself = self;ThrioIdCallback readyBlock = ^(id _){ThrioLogV(@"push entrypoint: %@, url:%@", entrypoint, url);__strong typeof(weakself) strongSelf = weakself;if ([strongSelf.topViewController isKindOfClass:NavigatorFlutterViewController.class] &&[[(NavigatorFlutterViewController*)strongSelf.topViewController entrypoint] isEqualToString:entrypoint]) {// 4.3.1 中分析} else {// 4.3.2 中分析};[NavigatorFlutterEngineFactory.shared startupWithEntrypoint:entrypoint readyBlock:readyBlock]; };這里開頭有一些多引擎的標(biāo)志處理,因 Thrio 的多引擎目前還在開發(fā)完善中,因此我們本節(jié)就不看它多引擎部分的代碼了,看看主體部分吧。根據(jù)容器類型,如果當(dāng)前(最上層)的 viewController 是 FlutterViewController(NavigatorFlutterViewController 是它的一層封裝)就走某邏輯,否則就是 NativeViewController 走另一端邏輯。
因此在要打開的頁面是 Flutter 頁面是,Thrio 和 Flutter Boost 不同,它不會一股腦的去創(chuàng)建容器,而是區(qū)分情況處理,這其實也是 Thrio 與 Flutter Boost 最大的不同:
4.3.1 Flutter 打開 Flutter
if ([strongSelf.topViewController isKindOfClass:NavigatorFlutterViewController.class] &&[[(NavigatorFlutterViewController*)strongSelf.topViewController entrypoint] isEqualToString:entrypoint]) {NSNumber *index = @([strongSelf thrio_getLastIndexByUrl:url].integerValue + 1);[strongSelf.topViewController thrio_pushUrl:urlindex:indexparams:paramsanimated:animatedfromEntrypoint:entrypointresult:^(NSNumber *idx) {if (idx && [idx boolValue]) {[strongSelf thrio_removePopGesture];}if (result) {result(idx);}} poppedResult:poppedResult]; } else {// Native 打開 Flutter 4.3.2 中分析 }這里又會走到我們 4.2 中分析到 thrio_pushUrl:
- (void)thrio_pushUrl:(NSString *)urlindex:(NSNumber *)indexparams:(id _Nullable)paramsanimated:(BOOL)animatedfromEntrypoint:(NSString * _Nullable)entrypointresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {NavigatorRouteSettings *settings = [NavigatorRouteSettings settingsWithUrl:urlindex:indexnested:self.thrio_firstRoute != nilparams:params];// ...省略 4.2 中的代碼if ([self isKindOfClass:NavigatorFlutterViewController.class]) {NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithDictionary:[settings toArguments]];[arguments setObject:[NSNumber numberWithBool:animated] forKey:@"animated"];NSString *entrypoint = [(NavigatorFlutterViewController*)self entrypoint];NavigatorRouteSendChannel *channel = [NavigatorFlutterEngineFactory.shared getSendChannelByEntrypoint:entrypoint];if (result) {[channel onPush:arguments result:^(id _Nullable r) {result(r && [r boolValue] ? index : nil);}];} else {[channel onPush:arguments result:nil];}} }核心是使用 MethodChannel 向 Dart 側(cè)發(fā)送 onPush 消息:
- (void)onPush:(id _Nullable)arguments result:(FlutterResult _Nullable)callback {[self _on:@"onPush" arguments:arguments result:callback]; }- (void)_on:(NSString *)methodarguments:(id _Nullable)argumentsresult:(FlutterResult _Nullable)callback {NSString *channelMethod = [NSString stringWithFormat:@"__%@__", method];[_channel invokeMethod:channelMethod arguments:arguments result:callback]; }Dart 側(cè)收到消息后,根據(jù)路由名找到 builder 生成一個 Route,之后會使用 Flutter 的 Navigator 去 push 這個 widget:
void _onPush() => _channel.registryMethodCall('__onPush__', ([arguments]) {final routeSettings = NavigatorRouteSettings.fromArguments(arguments);ThrioLogger.v('onPush:${routeSettings.name}');final animatedValue = arguments['animated'];final animated =(animatedValue != null && animatedValue is bool) && animatedValue;return ThrioNavigatorImplement.navigatorState?.push(routeSettings, animated: animated)?.then((it) {_clearPagePoppedResults();return it;});});因此,Thrio 這種場景下沒有像 Flutter Boost 那樣去創(chuàng)建一個 FlutterViewController,而是在已有的容器上使用 Navigator 去 push。所以在連續(xù)打開 Flutter 頁面這種場景下,Thrio 的內(nèi)存占用會低一些。
4.3.2 Native 打開 Flutter
if ([strongSelf.topViewController isKindOfClass:NavigatorFlutterViewController.class] &&[[(NavigatorFlutterViewController*)strongSelf.topViewController entrypoint] isEqualToString:entrypoint]) {// 4.3.1,Flutter 打開 Flutter } else {UIViewController *viewController = [strongSelf thrio_createFlutterViewControllerWithEntrypoint:entrypoint];[strongSelf thrio_pushViewController:viewControllerurl:urlparams:paramsanimated:animatedfromEntrypoint:entrypointresult:resultpoppedResult:poppedResult]; }從 Native 頁面打開 Flutter,會先執(zhí)行 thrio_createFlutterViewControllerWithEntrypoint,顧名思義,其實它就是創(chuàng)建一個 FlutterViewController:
- (UIViewController *)thrio_createFlutterViewControllerWithEntrypoint:(NSString *)entrypoint {UIViewController *viewController;NavigatorFlutterPageBuilder flutterBuilder = [ThrioNavigator flutterPageBuilder];if (flutterBuilder) {viewController = flutterBuilder();} else {viewController = [[NavigatorFlutterViewController alloc] initWithEntrypoint:entrypoint];}return viewController; }需要注意的是,這里框架會維護(hù)一個對象,如果之前創(chuàng)建過 FlutterViewController,它就會從緩存里去取出來,否則才會新建一個 FlutterViewController。
之后調(diào)用 thrio_pushViewController,這段邏輯和之前分析的 4.2 打開 Native 頁面是一樣的:
- (void)thrio_pushViewController:(UIViewController *)viewControllerurl:(NSString *)urlparams:(id _Nullable)paramsanimated:(BOOL)animatedfromEntrypoint:(NSString * _Nullable)entrypointresult:(ThrioNumberCallback _Nullable)resultpoppedResult:(ThrioIdCallback _Nullable)poppedResult {if (viewController) {NSNumber *index = @([self thrio_getLastIndexByUrl:url].integerValue + 1);__weak typeof(self) weakself = self;[viewController thrio_pushUrl:urlindex:indexparams:paramsanimated:animatedfromEntrypoint:entrypointresult:^(NSNumber *idx) {if (idx && [idx boolValue]) {__strong typeof(weakself) strongSelf = weakself;[strongSelf pushViewController:viewController animated:animated];}if (result) {result(idx);}} poppedResult:poppedResult];} }Thrio 的源碼當(dāng)然不止分析的這一點,還有很多索引維護(hù)、邊界處理、多引擎邏輯、場景性能優(yōu)化、生命周期與路由事件通知等邏輯沒有分析到,鑒于篇幅問題,僅分析一下主流程打通框架的脈絡(luò),剩下的過于細(xì)節(jié),本文不再一一分析。
下圖是本節(jié) Thrio 打開頁面的一個流程總結(jié):
雖然框架的實現(xiàn)上我們發(fā)現(xiàn) Thrio 較 Flutter Boost 要復(fù)雜一些,但是混合棧的容器更簡潔了——對于連續(xù)的 Flutter 頁面(Widget)只需要在當(dāng)前 FlutterViewController 打開即可,無需去創(chuàng)建新的容器。
5. 多 engine 模式
多引擎的架構(gòu)如圖所示:
官方設(shè)計是 FlutterEngine 對應(yīng)四個線程(Task Runner):
- Platform Task Runner
- UI Task Runner
- GPU Task Runner
- IO Task Runner
因此 Engine 是一個比較重的對象,之前筆者測試過,啟動一個 engine 主線程會耗時 30ms 左右,內(nèi)存占用增加 30MB。雖然內(nèi)存不占優(yōu),但主線程只占用 30ms 相比 RN 與 Webview 動輒初始化 100~200 ms 是好了不少。
多 engine 可能會帶來一些問題:
Thrio 有一套索引維護(hù)機(jī)制,結(jié)合多引擎和多 FlutterViewController,可以定位到每一個頁面的位置:
不可否認(rèn),多引擎帶來的隔離是一個好處,至于能帶來多少性能提升,還需要再測試一下。不過,多引擎模式是值得期待的混合開發(fā)框架模式。
參考資料:- Adding Flutter to exist app:https://flutter.dev/docs/development/add-to-app
- 閑魚基于Flutter的移動端跨平臺應(yīng)用實踐 http://www.cocoachina.com/cms/wap.php?action=article&id=24859
- 今日頭條 | 讓Flutter真正支持View級別的混合開發(fā):https://www.msup.com.cn/share/details?id=226
- hellobike/thrio:https://github.com/hellobike/thrio/blob/master/doc/Feature.md
- alibaba/flutter_boost:https://github.com/alibaba/flutter_boost
總結(jié)
以上是生活随笔為你收集整理的qt框架的开发模式_Flutter 混合开发框架模式探索的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 仪表盘数据显示_跟小白学P
- 下一篇: python中flag的用法_pytho