Flutter 混合开发(集成到原生 iOS 项目)

对于 Flutter 的业务应用,咱们更但愿它能够集成到已有的项目中,这篇详细的介绍下如何将 Flutter 集成到 iOS 项目工程中,对于后续的通讯、交互、管理等内容会在后面的篇章中介绍。ios

建立 Flutter 模块shell

建立 iOS 工程项目,命名为 FlutterMixDemo ,固然你也能够用已有的工程来集成。xcode

注意1:将咱们项目 BitCode 选项设置为 NO , Flutter 目前还不支持。app

接下来咱们须要建立 Flutter 模块,进入已有工程目录,这里拿个人工程目录举例:ide

flutterMix/FlutterMixDemo/  (FlutterMixDemo 是个人 iOS 工程项目)
进入在 flutterMix 目录下,终端执行命令:
flutter create -t module flutter_module

注意2:flutter_module 是本身命名的,但要记得字母都要小写,否则会报错。优化

该命令会建立一个 Flutter 项目模块,咱们能够看下它的项目结构及内容。ui

将 Flutter 模块以 pods 的方式加入到已有项目中spa

在咱们的已有项目 FlutterMixDemo 中初始化 pods ,固然若是你的项目中已初始化过 pods ,请忽略。设计

cd FlutterMixDemo
pod init

这时咱们项目中会多一个 Podfile 文件,咱们在该文件最后面添加命令以下:code

target 'FlutterMixDemo' do
end
# 新加命令
flutter_application_path = '../flutter_module'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)

注意3:flutter_application_path 是 Flutter 模块的路径,记得修改成你的模块名称。

添加好后,运行命令

pod install

配置 Dart 编译脚本

在项目Build Phases 选项中,点击左上角➕号按钮,选择 New Run Script Phase ,添加以下脚本

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed

使用 FlutterViewController

全部的 Flutter 页面公用一个Flutter实例 (FlutterViewController) 。

咱们已点击按钮后跳入 Flutter 页面举例:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(jumpToFlutter)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"jump to flutter" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor orangeColor]];
    button.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    button.frame = CGRectMake(95.0, 210.0, 160.0, 44.0);
    [self.view addSubview:button];
}

- (void)jumpToFlutter {
    FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
    [self.navigationController pushViewController:flutterViewController animated:YES];
}

不过这样跳转后自己 Flutter 页面也会有一个导航栏,原生也有一个,形成重复。固然咱们能够把 Flutter 页面的 appBar 去掉就能够,以下:

appBar: AppBar(
        title: Text('Flutter Page') ,
        leading: IconButton(icon: Icon(Icons.arrow_back_ios), onPressed:()=>Navigator.pop()),
      ),

不过针对总体的设计、管理、交互如何去处理优化,也是一个值得讨论的话题,我会接下来再介绍。

相关文章
相关标签/搜索