来了!Flutter混合开发专题一

前言

Flutter做为新一代移动端跨平台解决方案,相比于React Native等有很大的性能优点,因此不少公司已经开始研究Flutter并将其应用于实际项目中,目前包括闲鱼、美团、京东和今日头条等都已经在APP部分页面尝试使用了,那么它们这些应用都已经使用原生开发的很成熟了且代码量很是大,若是全面使用Flutter改造势必是一个浩大的工程,因此他们都使用Flutter混合开发的模式渐进式的对部分页面进行改造。html

接下来几篇文章咱们将分析若干种混合开发方案来为你们在现有APP中引入Flutter作参考。本篇咱们将先介绍Flutter官方提供的混合开发集成方案。java

官方集成方案

官方提供的集成步骤详见:android

github.com/flutter/flu…ios

根据官方集成方案将Flutter集成到现有APP工程中会有一些小问题在,后边集成的过程当中会提到。如下集成步骤咱们假定现有安卓和iOS的APP工程分别为flutter_host_android和flutter_host_ios,两个工程放在同一目录下,以下git

some/path/
  flutter_host_android/
  flutter_host_ios/
复制代码

注意:github

如下工程的建立基于Flutter channel为 stable 1.2.1版本shell

建立Flutter工程

根据官方说明,咱们须要建立一个Flutter module工程(是module而不是app),命令行定位到以上some/path/目录下,使用以下命令建立编程

flutter create --org=com.flutterbus.app --type=module flutter_module
复制代码

建立完成后flutter_module工程和安卓、iOS的APP工程在同一目录中,结构以下api

some/path/
  flutter_host_android/
  flutter_host_ios/
  flutter_module/
复制代码

使用Android Studio打开flutter_module项目,目录结构以下xcode

从目录结构中咱们能够看出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_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。项目最终运行的效果以下

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页面叠加跳转时内存不断增大,由于FlutterView和FlutterViewController每次跳转都会新建一个对象,从而Embedder层的AndroidShellHolder和FlutterEngine都会建立新对象,UI Thread、IO Thread、GPU Thread和Shell都建立新的对象,惟独共享的只有DartVM对象,可是RootIsolate也是独立的,因此Flutter页面以前的数据不能共享,这样就很难将一些全局性的公用数据保存在Flutter中,因此这套方案比较适合开发不带有共享数据的独立页面,可是页面又不能太多,由于建立的Flutter页面越多内存就会暴增,尤为是在iOS上还有内存泄露的问题。

有须要本文中源代码的同窗能够给本公众号发消息留下你的邮箱地址。其实代码也比较简单,根据整个步骤的说明基本就能本身搞定了。

说明:

文章转载自对应的“Flutter编程指南”微信公众号,更多Flutter相关技术文章打开微信扫描二维码关注微信公众号获取。

相关文章
相关标签/搜索