参考:https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps
本文代码:https://github.com/yonglinwang002/TestFlutter
一、生成Flutter 模块
假设已有工程 TestFlutter
$ cd TestFlutter/
$ flutter create -t module flutter_library
执行后会生成
flutter_library 目录
结构如下
二、使用宿主工程依赖Flutter模块
在主工程中增加一个 Group 如名为Flutter
生成后结构
TestFlutter/
Flutter/
Flutter.xcconfig
TestFlutter/
AppDelegate.h
AppDelegate.m
:
Debug.xcconfig
Release.xcconfig
编辑Flutter.xcconfig 文件
#include "../flutter_library/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
Debug.xcconfig文件
#include "../Flutter/Flutter.xcconfig"
Release.xcconfig文件
#include "../Flutter/Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
使用xcconfig相应配置
三、设置执行Flutter的脚本
在Run Script中增加
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
四、执行脚本并把Framework加入工程
Cmd+B,Build工程,编译后,Flutter目录中生成如下
把其中的flutter_assets 目录以及Flutter.framework加入到工程的Flutter Group中
注意添加flutter_assets目录时,选择 Create forlder references !!!! (我就是这里没注意,后面始终出错)
五、添加调用Flutter语句
这里就没有什么好说的了,
#import "Flutter/Flutter.h"
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor orangeColor]];
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];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)handleButtonAction {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
flutterViewController.view.frame = [UIScreen mainScreen].bounds;
// [flutterViewController setInitialRoute:@"route1"];//如果设置了router,可以到不同的页面
[self presentViewController:flutterViewController animated:NO completion:nil];
}
Cmd+R吧,就出来了
这里说一个热重载的方法 (Hot Reload) 在终端上
$ cd flutter_library
$ flutter attach
Waiting for a connection from Flutter on iPhone X...
然后,在XCode中 Cmd+R 执行,待进入到FlutterView页面时,
终端变成如下
这时如果修改了dart文件 ,再按r就可以重新载入
q 退出