移动App混合开发之Flutter篇(2)---iOS工程配置

用pod集成Flutter

打开xcode新建iOS工程,然后关闭xcode
在iOS工程根目录执行

1
2
pod init
pod install --no-repo-update --verbose

以后用xcworkspace打开工程,不要用xcodeproj了

xcworkspace

Podfile 中添加下面代码

1
2
3
#这个路径指向flutter工程路径
flutter_application_path = '../Master-Flutter/master_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

在target节点下添加

1
2
install_all_flutter_pods(flutter_application_path)

Podfile

目前iOS集成Flutter已经完成,寥寥数行代码而已.

在 iOS中把Flutter工程的代码Run起来

AppDelegate.h 继承FlutterAppDelegate,增加属性FlutterEngine

1
2
3
4
5
6
7
8
9
10
#import <UIKit/UIKit.h>
@import UIKit;
@import Flutter;

@interface AppDelegate :FlutterAppDelegate // More on the FlutterAppDelegate below.
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end



AppDelegate.m 重写didFinishLaunchingWithOptions方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#import "AppDelegate.h"
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];
// Runs the default Dart entrypoint with a default Flutter route.
[self.flutterEngine run];
// Used to connect plugins (only if you have plugins with iOS platform code).
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}



ViewController.m

在ViewController.m的viewDidLoad方法新增代码

导包

1
2
3
@import Flutter;
#import "ViewController.h"
#import "AppDelegate.h"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16


- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

// Make a button to call the showFlutter function when pressed.
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];
}

新增方法

1
2
3
4
5
6
7
8
- (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];
}

ViewController.m

运行即可

运行效果