少停
>
Flutter~iOS原生工程中添加Flutter模块
今天,学习下,如何在iOS原生工程中集成Flutter模块
- ok,首先我们使用Xcode新建一个iOS原生工程,先放着.
然后通过flutter create -t module flutter_module
新建一个flutter的模块,这里名字随意.以flutter_module
为例.
- 然后在iOS原生工程中,使用
pod
导入flutter:
首先,终端上先通过pod init
为原生工程创建Podfile文件.
然后在该Podfile文件中添加以下:
1 2 3
| flutter_application_path = '../flutter_module/' eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
|
注意路径正确.
终端 cd
到iOS原生项目根目录下. 执行pod install
通过点击XXXX.xcworkspace文件打开Xcode.
找到”TAGGETS”->”Build Settings”->”Enable Bitcode”
首先把项目bitcode关闭.
找到”TAGGETS”->”Build Settings”->”Enable Phases”.
点击+号,新建一个”New Run Script Phase”.
其中加入:
1 2 3
| "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
|
然后,把它移动Target Dependencied下面.
ok.Xcode build下,正确情况下是工程好的.集成步骤完毕.
然后我们在 ViewController.m
中通过presentViewController
的方式跳至flutter模块即可.
首先,引入
1 2 3
| #import <Flutter/Flutter.h> #import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
|
其中,可以为flutter模块传个参数,通过
setInitialRoute
.
该文件完整代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| // // ViewController.m // iOSAddFlutter // // Created by Shaoting Zhou on 2019/5/29. // Copyright © 2019 Shaoting Zhou. All rights reserved. //
#import "ViewController.h"
#import <Flutter/Flutter.h> #import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [[UIButton alloc]init]; [button setTitle:@"跳至Flutter模块" forState:UIControlStateNormal]; button.backgroundColor=[UIColor redColor]; button.frame = CGRectMake(50, 50, 200, 100); [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; [button addTarget:self action:@selector(buttonPrint) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; // Do any additional setup after loading the view. }
- (void)buttonPrint{ FlutterViewController * flutterVC = [[FlutterViewController alloc]init]; [flutterVC setInitialRoute:@"我是Native传给FLutter模块的"]; [self presentViewController:flutterVC animated:true completion:nil]; }
@end
|
在flutter_module
模块中,通过window.defaultRouteName
的方式即可获取到iOS原生传过去的值.其中需要引入 import 'dart:ui';
源码
效果图: