來了!Flutter混合開發專題一

Flutter程式設計指南發表於2019-04-22

前言

Flutter作為新一代移動端跨平臺解決方案,相比於React Native等有很大的效能優勢,所以很多公司已經開始研究Flutter並將其應用於實際專案中,目前包括閒魚、美團、京東和今日頭條等都已經在APP部分頁面嘗試使用了,那麼它們這些應用都已經使用原生開發的很成熟了且程式碼量非常大,如果全面使用Flutter改造勢必是一個浩大的工程,所以他們都使用Flutter混合開發的模式漸進式的對部分頁面進行改造。

接下來幾篇文章我們將分析若干種混合開發方案來為大家在現有APP中引入Flutter做參考。本篇我們將先介紹Flutter官方提供的混合開發整合方案。

官方整合方案

官方提供的整合步驟詳見:

github.com/flutter/flu…

根據官方整合方案將Flutter整合到現有APP工程中會有一些小問題在,後邊整合的過程中會提到。以下整合步驟我們假定現有安卓和iOS的APP工程分別為flutter_host_android和flutter_host_ios,兩個工程放在同一目錄下,如下

some/path/
  flutter_host_android/
  flutter_host_ios/
複製程式碼

注意:

以下工程的建立基於Flutter channel為 stable 1.2.1版本

建立Flutter工程

根據官方說明,我們需要建立一個Flutter module工程(是module而不是app),命令列定位到以上some/path/目錄下,使用如下命令建立

flutter create --org=com.flutterbus.app --type=module flutter_module
複製程式碼

建立完成後flutter_module工程和安卓、iOS的APP工程在同一目錄中,結構如下

some/path/
  flutter_host_android/
  flutter_host_ios/
  flutter_module/
複製程式碼

使用Android Studio開啟flutter_module專案,目錄結構如下

來了!Flutter混合開發專題一

從目錄結構中我們可以看出Flutter module專案中的安卓和iOS工程和Flutter app專案中的不同,他們都是隱藏的工程,其實官方是不建議在這兩個原生工程中新增任何平臺程式碼的,這兩個工程用於對Flutter專案進行測試。

根據模板生成的main.dart中的程式碼不是圖中這樣的,我們稍微做了一些修改,僅供參考,這裡的defaultRouteName是由平臺原生層傳入的routeName,我們可以根據不同的routeName展示不同的頁面Widget。這裡面的程式碼修改後邊再做說明,下面我們看一下具體的整合步驟。

安卓整合

Flutter工程下的aar產物構建

在將flutter_module專案整合到安卓原生工程flutter_host_android之前,需要先將flutter_module專案中的安卓工程構建出一個aar,命令列切換到flutter_module目錄下,執行以下命令

cd .android
./gradlew assembleDebug
複製程式碼

執行完成後.android/Flutter/build/output/aar/目錄下就會有一個flutter-debug.aar產物生成。

原生工程配置

修改原生工程flutter_host_android下的app module中的build.gradle,在android{}配置中新增一下內容

compileOptions {
  sourceCompatibility 1.8
  targetCompatibility 1.8
}
複製程式碼

必須新增,否則在執行':app:mergeExtDexDebug'任務時會報如下錯誤

org.gradle.api.UncheckedIOException: Failed to capture fingerprint of input files for task ':app:mergeExtDexDebug' property 'dexFiles' during up-to-date check.
	at org.gradle.api.internal.changedetection.state.CacheBackedTaskHistoryRepository.fingerprintTaskFiles(CacheBackedTaskHistoryRepository.java:360)
	...
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
The dependency contains Java 8 bytecode. Please enable desugaring by adding the following to build.gradle
android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}
See https://developer.android.com/studio/write/java8-support.html for details. Alternatively, increase the minSdkVersion to 26 or above.

	at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
	...
複製程式碼

然後再工程的settings.gradle中增加如下程式碼

// 這句應該已經存在了
include ':app'

//增加內容
setBinding(new Binding([gradle: this]))
evaluate(new File(
        settingsDir.parentFile,
        'flutter_module/.android/include_flutter.groovy'
))
複製程式碼

根據include_flutter.groovy中的內容,這段配置就是將flutter_module中安卓flutter module自身和所依賴的外掛包含進settings.gradle的上下文中,以便於app module配置對“:flutter”的依賴。

在app的build.gradle中新增“:flutter”依賴

dependencies {
  .
  .
  implementation project(':flutter')
}
複製程式碼

配置完成後,點選來了!Flutter混合開發專題一同步按鈕,這時就可以使用flutter_module中提供的工具類了。

原生和Flutter互動

flutter_host_android工程的java原始碼包下新建一個FlutterDemoActivity類,onCreate方法中的實現如下

public static final String CHANNEL_NAME = "com.flutterbus/demo";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		// 獲取由上一個頁面傳過來的routeName
        String routeName = "";
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            routeName = intent.getExtras().getString("routeName");
        }

		 // 根據指定routeName建立FlutterView用來展示對應dart中的Widget
        FlutterView flutterView = Flutter.createView(this, this.getLifecycle(), routeName);
        
        // 建立Platform Channel用來和Flutter層進行互動
        new MethodChannel(flutterView, CHANNEL_NAME).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                methodCall(methodCall, result);
            }
        });
        setContentView(flutterView);
    }
    
    /**
     * 處理dart層傳來的方法呼叫
     */
    private void methodCall(MethodCall call, MethodChannel.Result result) {
        if (call.method.equals("gotoNativePage")) {
            startActivity(new Intent(this, NativeActivity.class));
            result.success(true);
        } else {
            result.notImplemented();
        }
    }
複製程式碼

從安卓原生頁面跳轉到FlutterDemoActivity頁面使用如下方法將routeName傳遞過去

Intent intent = new Intent(this, FlutterDemoActivity.class);
Bundle bundle = new Bundle();
bundle.putString("routeName", "first");
intent.putExtras(bundle);
startActivity(intent);
複製程式碼

routeName在Flutter端是如何起到作用的呢,可以看下Flutter module中dart程式碼

void main() => runApp(_widgetForRoute(window.defaultRouteName));

Widget _widgetForRoute(String route) {
  switch (route) {
    case 'first':
      return MyApp();
    case 'second':
      return MyApp();
    default:
      return Center(
        child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
      );
  }
}
.
.
複製程式碼

java中建立FlutterView時其實就是將routeName設定為window的defaultRouteName,這樣在dart端執行的時候就會根據defaultRouteName來展示對應的Widget了。而上面java層我們定義了Platform Channel,這樣Flutter端就可以在dart層通過MethodChannel傳遞訊息給java層從而實現兩端的互動。

static final String channelName = "com.flutterbus/demo";

Future<Null> jumpToNativePage() async {
	MethodChannel methodChannel = MethodChannel(channelName);
	await methodChannel.invokeMethod("gotoNativePage");
}
複製程式碼

至此,安卓原生工程整合Flutter就完成了,後續我們想用Flutter實現UI介面都可以在Flutter module工程中編寫,原生想跳轉到指定Flutter頁面設定好routeName即可,dart的main函式會根據routeName來跳轉到不同的Widget。專案最終執行的效果如下

來了!Flutter混合開發專題一

iOS整合

原生工程配置

整合Flutter module工程到flutter_host_ios工程需要Cocoapods依賴項管理器,請確保本地安裝了cocoapods,如果未安裝,可以參考:cocoapods.org/

如果flutter_host_ios工程中已經使用了cocoapods,將下列配置新增到工程的Podfile檔案中

flutter_application_path = 'some/path/flutter_module/'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
複製程式碼

如果沒有使用cocoapods,則在iOS工程根目錄下建立一個新的Podfile檔案,配置如下資訊

platform :ios, '9.0'
use_frameworks!

target 'flutter_host_ios' do
  flutter_application_path = 'some/path/flutter_module/'
  eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
end
複製程式碼

配置完成後,執行pod install確保Flutter.framework新增到iOS工程中。此時flutter_host_ios工程目錄下的目錄結構

flutter_host_ios/
  flutter_host_ios/
  flutter_host_ios.xcodeproj
  flutter_host_ios.xcworkspace
  Podfile
  Podfile.lock
  Pods/
複製程式碼

雙擊iOS工程目錄中的flutter_host_ios.xcworkspace檔案會使用xcode開啟。

下面進行如下配置

  1. 因為Flutter現在不支援bitcode,需要禁用專案TARGETS的Build Settings-> Build Options-> Enable Bitcode部分中的ENABLE_BITCODE標誌。

  2. 找到專案TARGETS的Build Phases,點選左上角+號選擇New Run Script Phase新增Run Script,在Shell欄位下新增下面兩行指令碼

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
複製程式碼

新增完成後拖拽Run Script欄到Target Dependencies欄下即可。然後執行快捷鍵⌘B構建一下專案。接下來我們就可以在flutter_host_ios專案中新增原生與flutter互動的程式碼了。

原生與Flutter互動

首先,我們將flutter_host_ios中的AppDelegate改為繼承自FlutterAppDelegate,並在標頭檔案中定義FlutterEngine變數供後續使用

#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>

@interface AppDelegate : FlutterAppDelegate
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end
複製程式碼

AppDelegate.m檔案中的完成應用啟動的生命週期函式中實現flutterEngine

#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Only if you have Flutter Plugins

#include "AppDelegate.h"

@implementation AppDelegate

// This override can be omitted if you do not have any Flutter Plugins.
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  self.flutterEngine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:nil];
  [self.flutterEngine runWithEntrypoint:nil];
  [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end
複製程式碼

接下來我們在原生介面中新增一個按鈕,按鈕的點選事件觸發後跳轉到Flutter頁面

#import <Flutter/Flutter.h>
#import "AppDelegate.h"
#import "ViewController.h"

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(handleButtonAction)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Press me" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];
}

- (void)handleButtonAction {
    FlutterEngine *flutterEngine = [(AppDelegate *)[[UIApplication sharedApplication] delegate] flutterEngine];
    FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
    [self presentViewController:flutterViewController animated:false completion:nil];
}
@end
複製程式碼

根據官方說明我們想在FlutterViewController中顯示first對應的Flutter Widget,那麼需要在flutterViewController下方新增一行指定初始化routeName的程式碼

[flutterViewController setInitialRoute:@"first"];
複製程式碼

但是執行應用之後,我們發現點選按鈕後並沒有跳轉指定first對應的頁面,而是顯示了Flutter中的一個預設頁面,dart中的switch語句走到了以下分支

default:
      return Center(
        child: Text('Unknown route: $route', textDirection: TextDirection.ltr)
複製程式碼

分析原始碼後發現在AppDelegate初始化flutterEngine後,立即呼叫了[self.flutterEngine runWithEntrypoint:nil],這句程式碼是建立Flutter engine環境並啟動引擎,這時候其實已經執行了main.dart中的main方法,此時window.defaultRouteName為空,所以展示了上面default分支的Widget,後邊建立FlutterViewController後設定的routeName是起不到作用的。runWithEntrypoint方法對應的原始碼參考

- (BOOL)runWithEntrypoint:(NSString*)entrypoint {
  return [self runWithEntrypoint:entrypoint libraryURI:nil];
}

- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
  if ([self createShell:entrypoint libraryURI:libraryURI]) {
    [self launchEngine:entrypoint libraryURI:libraryURI];
  }

  return _shell != nullptr;
}

- (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
   ...
   _shell = shell::Shell::Create(std::move(task_runners),
                                  std::move(settings),
                                  on_create_platform_view,
                                  on_create_rasterizer
                                  );
   ...
   return _shell != nullptr;
}

- (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil {
  self.shell.GetTaskRunners().GetUITaskRunner()->PostTask(fml::MakeCopyable(
      [engine = _shell->GetEngine(),
       config = [_dartProject.get() runConfigurationForEntrypoint:entrypoint
                                                     libraryOrNil:libraryOrNil]  //
  ]() mutable {
        if (engine) {
          // 這裡開始啟動dart應用程式執行main.dart中的main函式
          auto result = engine->Run(std::move(config));
          ...
        }
      }));
}
複製程式碼

那麼這個問題怎麼解決呢,我們可以使用FlutterViewController自己建立的FlutterEngine而不去自己建立,這樣在按鈕點選跳轉事件處理時執行如下程式碼

FlutterViewController *flutterViewController = [[FlutterViewController alloc] init];
    [flutterViewController setInitialRoute:@"first"];
    FlutterMethodChannel* methodChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"com.flutterbus/demo"
                                            binaryMessenger:flutterViewController];
    
    [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        if ([@"gotoNativePage" isEqualToString:call.method]) {
            NSLog(@"gotoNativePage received!!!!!!!");
            NativeViewController *nativeViewController = [[NativeViewController alloc] init];
            [flutterViewController presentViewController:nativeViewController animated:NO completion:nil];
            result(@YES);
        } if([@"exit" isEqualToString:call.method]) {
            [flutterViewController dismissViewControllerAnimated:NO completion:nil];
            result(@YES);
        } else {
            result(FlutterMethodNotImplemented);
        }
    }];
    [self presentViewController:flutterViewController animated:NO completion:nil];
複製程式碼

以上程式碼中我們同時定義了一個FlutterMethodChannel以供接收Flutter端的訊息做處理,這樣就實現了Flutter和原生的互動,專案最終執行後效果如下

來了!Flutter混合開發專題一

總結

以上就是官方提供的混合開發方案了,這個方案有一個巨大的缺點,就是在原生和Flutter頁面疊加跳轉時記憶體不斷增大,因為FlutterView和FlutterViewController每次跳轉都會新建一個物件,從而Embedder層的AndroidShellHolder和FlutterEngine都會建立新物件,UI Thread、IO Thread、GPU Thread和Shell都建立新的物件,唯獨共享的只有DartVM物件,但是RootIsolate也是獨立的,所以Flutter頁面之前的資料不能共享,這樣就很難將一些全域性性的公用資料儲存在Flutter中,所以這套方案比較適合開發不帶有共享資料的獨立頁面,但是頁面又不能太多,因為建立的Flutter頁面越多記憶體就會暴增,尤其是在iOS上還有記憶體洩露的問題。

有需要本文中原始碼的同學可以給本公眾號發訊息留下你的郵箱地址。其實程式碼也比較簡單,根據整個步驟的說明基本就能自己搞定了。

說明:

文章轉載自對應的“Flutter程式設計指南”微信公眾號,更多Flutter相關技術文章開啟微信掃描二維碼關注微信公眾號獲取。

來了!Flutter混合開發專題一

相關文章