从0开始模拟Flutter-module嵌入iOS原生项目的流程。
环境是:xcode13.1、Android studio Arctic Fox | 2020.3.1 Patch 4、Flutter SDK 2.10.1
1、创建文件夹和文件
根据官网的文档,首先,在桌面创建一个名为native_import_flutter_demo的文件夹,然后在该文件夹内分别创建了iOS_demo、flutter_module两个文件。关于flutter_module,可以用命令行:
flutter create --template module flutter_module
也可直接用Android studio创建2、添加Podfile
这个可以在终端创建一个,也可从别的地方拷贝一个
3、Podfile配置
flutter_application_path = '../flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'iOS_demo' do
install_all_flutter_pods(flutter_application_path)
end
4、执行 pod install
终端 cd 到 iOS_demo 目录,执行pod install
5、运行iOS项目
如果出现如下错误:
运行成功不报错,则表示flutter-module嵌入成功。
6、添加一个Flutter页面
AppDelegate.h:
#import <UIKit/UIKit.h>
@import Flutter;
@interface AppDelegate : FlutterAppDelegate
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end
AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];
[self.flutterEngine run];
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
ViewController.m:
@import Flutter;
#import "AppDelegate.h"
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:@selector(showFlutter)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show Flutter!" forState:UIControlStateNormal];
button.backgroundColor = UIColor.blueColor;
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
- (void)showFlutter {
FlutterEngine *flutterEngine =((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
FlutterViewController *flutterViewController =[[FlutterViewController alloc]initWithEngine:flutterEngine nibName:nil bundle:nil];
[self presentViewController:flutterViewController animated:YES completion:nil];
}
@end
7、再次运行iOS项目
出现如下问题:
于是打开给的参考地址,设置如下:
再次运行iOS,提示"无法打开“iproxy”,因为无法验证开发者。"(忘了截图)
我查看隐私设置吗,已经是"允许任何来源"
抱着试试的态度,再次执行(允许任何来源)命令:sudu spctl --master-disable,页面变成了这样
点击了“允许”后,再次运行,弹出了如下提示:
点击“打开”即可。至此,运行成功。
7、在flutter_module里执行flutter attach 进行热更新
修改flutter的元素,输入r来更新。
Demo的github地址:native_import_flutter_demo