添加Flutter到現(xiàn)有iOS的項目
創(chuàng)建iOS項目
如果你已經(jīng)有iOS項目如失,可以直接使用瘸恼。這里我們先創(chuàng)建一個空的iOS項目來模擬已有的項目,取名叫TestOne
創(chuàng)建Flutter模塊
進(jìn)入你的項目同一層目錄奥吩,假如你的項目是在...path1/path2/yourApp,那么你應(yīng)該進(jìn)入到path2目錄中
$ cd ...path1/path2/
$ flutter create -t module my_flutter
上面的命令會創(chuàng)建一個flutter的項目模塊,在flutter文件夾中有一個.ios的隱藏文件夾蕊梧,里面包裹了Cocoapods 和 Ruby 腳本霞赫。
完成后的項目目錄是這樣的:
將Flutter模塊作為依賴添加到主項目
添加Flutter需要使用cocoapods,如果你還沒有安裝肥矢,可以參考這里的詳細(xì)教程:安裝cocoapods
創(chuàng)建Podfile文件
如果你的工程已經(jīng)使用了Cocoapods端衰,就可以跳過此步驟。
安裝完成之后甘改,切換到工程的文件夾下:
cd 工程路徑
初始化pod的環(huán)境:
pod init
此時工程中會出現(xiàn)一個Podfile文件旅东,添加項目依賴的第三方庫就在這個文件中配置。
編輯Podfile文件添加最后兩行代碼:
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'TestOne' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for TestOne
target 'TestOneTests' do
inherit! :search_paths
# Pods for testing
end
target 'TestOneUITests' do
inherit! :search_paths
# Pods for testing
end
end
#新添加的代碼
flutter_application_path = '../my_flutter'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
其中flutter_application_path代表你的flutter模塊路徑楼誓。
運(yùn)行
pod install
為編譯Dart 代碼添加build phase
打開iOS項目玉锌,選中TARGETTestOne
項目的Build Phases
選項,點擊左上角+
號按鈕,選擇New Run Script Phase
,將下面的shell腳本添加到輸入框中:
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
如下圖所示:
然后需要編譯一下項目:Command + B
疟羹。
如果你遇到了類似的這個問題:
FlutterPluginRegistrant/libFlutterPluginRegistrant.a(GeneratedPluginRegistrant.o)' does not contain bitcode.You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.for architecture arm64
將EnableBitCode關(guān)掉就行主守,因為目前Flutter目前還不支持BitCode。
在主app中使用FlutterViewController
修改AppDelegate.h
繼承自FlutterAppDelegate:
#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>
@interface AppDelegate : FlutterAppDelegate
@end
修改AppDelegate.m
文件:
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Only if you have Flutter Plugins
#include "AppDelegate.h"
@implementation AppDelegate
// This override can be omitted if you do not have any Flutter Plugins.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
如果你是Swift代碼榄融,可以修改AppDelegate.swift
這個文件:
import UIKit
import Flutter
import FlutterPluginRegistrant // Only if you have Flutter Plugins.
@UIApplicationMain
class AppDelegate: FlutterAppDelegate {
// Only if you have Flutter plugins.
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self);
return super.application(application, didFinishLaunchingWithOptions: launchOptions);
}
}
但是如果你的delegate已經(jīng)是繼承于別的類的時候参淫,可以通過讓你的delegate實現(xiàn)FlutterAppLifeCycleProvider
協(xié)議:
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Only if you have Flutter Plugins
@interface AppDelegate : UIResponder <UIApplicationDelegate, FlutterAppLifeCycleProvider>
@property (strong, nonatomic) UIWindow *window;
@end
然后生命周期方法應(yīng)該由FlutterPluginAppLifeCycleDelegate來代理:
@implementation AppDelegate
{
FlutterPluginAppLifeCycleDelegate *_lifeCycleDelegate;
}
- (instancetype)init {
if (self = [super init]) {
_lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init];
}
return self;
}
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self]; // Only if you are using Flutter plugins.
return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions];
}
// Returns the key window's rootViewController, if it's a FlutterViewController.
// Otherwise, returns nil.
- (FlutterViewController*)rootFlutterViewController {
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([viewController isKindOfClass:[FlutterViewController class]]) {
return (FlutterViewController*)viewController;
}
return nil;
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
[super touchesBegan:touches withEvent:event];
// Pass status bar taps to key window Flutter rootViewController.
if (self.rootFlutterViewController != nil) {
[self.rootFlutterViewController handleStatusBarTouches:event];
}
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
[_lifeCycleDelegate applicationDidEnterBackground:application];
}
- (void)applicationWillEnterForeground:(UIApplication*)application {
[_lifeCycleDelegate applicationWillEnterForeground:application];
}
- (void)applicationWillResignActive:(UIApplication*)application {
[_lifeCycleDelegate applicationWillResignActive:application];
}
- (void)applicationDidBecomeActive:(UIApplication*)application {
[_lifeCycleDelegate applicationDidBecomeActive:application];
}
- (void)applicationWillTerminate:(UIApplication*)application {
[_lifeCycleDelegate applicationWillTerminate:application];
}
- (void)application:(UIApplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
[_lifeCycleDelegate application:application
didRegisterUserNotificationSettings:notificationSettings];
}
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
[_lifeCycleDelegate application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[_lifeCycleDelegate application:application
didReceiveRemoteNotification:userInfo
fetchCompletionHandler:completionHandler];
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options {
return [_lifeCycleDelegate application:application openURL:url options:options];
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
return [_lifeCycleDelegate application:application handleOpenURL:url];
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
sourceApplication:(NSString*)sourceApplication
annotation:(id)annotation {
return [_lifeCycleDelegate application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (void)application:(UIApplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
completionHandler:(void (^)(BOOL succeeded))completionHandler NS_AVAILABLE_IOS(9_0) {
[_lifeCycleDelegate application:application
performActionForShortcutItem:shortcutItem
completionHandler:completionHandler];
}
- (void)application:(UIApplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
completionHandler:(nonnull void (^)(void))completionHandler {
[_lifeCycleDelegate application:application
handleEventsForBackgroundURLSession:identifier
completionHandler:completionHandler];
}
- (void)application:(UIApplication*)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[_lifeCycleDelegate application:application performFetchWithCompletionHandler:completionHandler];
}
- (void)addApplicationLifeCycleDelegate:(NSObject<FlutterPlugin>*)delegate {
[_lifeCycleDelegate addDelegate:delegate];
}
@end
使用FlutterViewController
在ViewController.m
中添加測試代碼:
#import <Flutter/Flutter.h>
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
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];
}
- (void)handleButtonAction {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
[self presentViewController:flutterViewController animated:false completion:nil];
}
@end
swift版:
import UIKit
import Flutter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type:UIButtonType.custom)
button.addTarget(self, action: #selector(handleButtonAction), for: .touchUpInside)
button.setTitle("Press me", for: UIControlState.normal)
button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
button.backgroundColor = UIColor.blue
self.view.addSubview(button)
}
@objc func handleButtonAction() {
let flutterViewController = FlutterViewController()
self.present(flutterViewController, animated: false, completion: nil)
}
}
現(xiàn)在運(yùn)行代碼,點擊按鈕愧杯,就能看到一個全屏的Flutter界面在你的app上涎才。
你也可以設(shè)置路由跳轉(zhuǎn)的別的組件上:
- Objective-C:
[flutterViewController setInitialRoute:@"route1"];
- Swift:
flutterViewController.setInitialRoute("route1")
你可以在展示FlutterViewController之前,在Dart代碼中使用SystemNavigator.pop()
將其彈出展示棧(就像iOS原生那樣)力九。
例子截圖:
點擊按鈕跳轉(zhuǎn)到flutter頁面:
使用熱重載的方法
熱重載指的是不用重新啟動就看到修改后的效果耍铜,類似web網(wǎng)頁開發(fā)時保存就看到效果的方式。
進(jìn)入flutter模塊跌前,執(zhí)行命令:
$ cd some/path/my_flutter
$ flutter attach
Waiting for a connection from Flutter on iPhone XR...
接下來在xcode中啟動你的app棕兼,進(jìn)入到flutter的頁面,此時你應(yīng)該在控制臺(終端)看到如下信息:
<table><tr><td bgcolor=#D1EEEE>?? To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
An Observatory debugger and profiler on Android SDK built for x86 is available at: http://127.0.0.1:61513/
For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".
</td></tr></table>
你可以在my_flutter
中編輯Dart code抵乓,然后在終端輸入r來使用熱重載伴挚。你也可以在瀏覽器中輸入上面的URL來查看斷點、分析內(nèi)存和其他的調(diào)試任務(wù)灾炭。
歡迎繼續(xù)學(xué)習(xí)相關(guān)的其他系列教程茎芋,關(guān)注我們TryEnough