開篇
開局一張圖,其他全靠_?
目前flutter框架還比較新,又是谷歌家的東西,所以網上的文章基本都是講安卓和flutter混合開發的,沒有iOS和Flutter混合開發的比較詳細的步驟實操。
混編的前提是你的電腦必須有flutter環境,不會配的請先谷歌教程配置完后再來查看此混編教程。
正題
因為本文要講的是iOS,所以正常情況下的環境是macOS + Xcode + flutter環境(v0.8.2-beta);再加上flutter 需要的的dart語言編輯器 Android Studio 、IntelliJ IDEA 或 Visual Studio Code (VS Code) ;因為flutter是多平臺,所以也要安裝安卓相關的SDK。
本教程是基于flutter環境版本v0.8.2-beta
環境配好后,命令行輸入:flutter doctor -v
, 確保Flutter
、 Android toolchain
、iOS toolchain
、 Connected devices
(連接中的設備,這個列表是你打開你Xcode虛擬機或者安卓虛擬機的時候才會有) 都不是[?]這個符號,則說明你的環境OK了 【也要注意編輯器的flutter環境】
Xcode工程項目配置
Xcode項目的開始
最權威的教程當然是flutter自家的混編wiki,iOS部分我英文理解能力不是很好,實際操作的時候也按照教程操作了一遍,再和網上教程總結了一遍,一路踏坑而出。
- Flutter混合開發還不支持bit code,所以在iOS工程檢查項目并關閉bit code
- flutter module創建 (不要耦合近Xcode項目中,最好放到與項目目錄同級)
這里因為使用的是flutter環境(v0.8.2-beta),應該也是很新的分支。看網上說明flutter的master才是最新的分支。先用beta創建module,如果創建不成功再切換master分支進行創建
如果創建不成功,請切換master分支試一下;執行
flutter channel master
- flutter module 重要文件分析 (部分是隱藏文件,記得查看全部)
-
創建Xcode項目中的Config文件,引向flutter module
新建
Config
目錄,管理Xcode工程的配置銜接文件,分別創建Flutter.xcconfig
、Debug.xcconfig
、Release.xcconfig
三個配置文件;其中Flutter.xcconfig
是指向外目錄flutter module的Generated.xcconfig
文件路徑引用文件,其他兩個代表Xcode的環境配置文件。
- 三個文件的引入內容 (所引用的都是絕對路徑,最終都是指引到
Generated.xcconfig
)
In Flutter.xcconfig
:
#include "../../flutter_module/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
In Debug.xcconfig
:
#include "Flutter.xcconfig"
In Release.xcconfig
:
#include "Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
這里有個值得注意的地方,如果你是使用的pod管理你的項目,則
Debug.xcconfig
、Release.xcconfig
都需要添加一行pod的引用
- Xcode project環境配置選擇
- 最重要: 引入
xcode-backend.sh
在iOS工程里添加運行腳本(創建Run Scrip) "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
,并且確保Run Script
這一行在"Target dependencies"
或者 "Check Pods Manifest.lock"
后面。
此時點擊Xcode的運行,會執行到xcode-backend.sh
腳本;此時在iOS工程目錄,也會生成一個Flutter文件夾,里面是Flutter工程的產物(這個就是flutter最終與Native交互的產物)
- 添加flutter編譯產物
右鍵項目 - Add Files to 'xxx'
【Options先選Create groups
】,選擇Flutter
目錄
但是flutter_assets
并不能使用Create groups
的方式添加,只能使用Creat folder references
的方式添加進Xcode項目內,否則跳轉flutter會頁面渲染失?。撁婵瞻祝?/p>
應該刪除
flutter_assets
,文件夾再Add Files to 'xxx'
,選擇Creat folder references
;最終如下圖
將iOS工程目錄下的Flutter文件夾添加到工程,然后確保文件夾下的兩個framework添加到Embeded Binaries
里
至此,Xcode與Flutter之間混編配置完成,兩個項目文件已經關聯上了。這時候你就可以修改main.dart
文件內容,重新編譯運行Xcode 則APP.framework
自動會被編譯成最新的flutter代碼。
項目中使用pod管理情況
一、舊項目沒使用pod管理,混編后又想pod管理
- 1、先刪除Xcode工程項目中的Run Script
- 2、
pod init
- 3、在生成的pod file文件寫你要增加的第三方框架,如
pod 'AFNetworking’
- 4、
pod install
- 5、(使用.xcworkspace打開項目)重新配置Run Script
- 6、修改
Debug.xcconfig
、Release。xcconfig
都需要增加一行pod config文件引用:(自己查看自己的Pods目錄文件路徑, release就使用.release.xcconfig)
#include "Flutter.xcconfig"
// 下面為pod引入需要增加的一行
#include "Pods/Target Support Files/Pods-iOSBridgeFlutterDemo/Pods-iOSBridgeFlutterDemo.debug.xcconfig"
- 7、項目重新編譯,Success
二、如果舊項目已經使用pod管理
- 如果項目ignore Pods文件夾, 則走一方法中的1、4、5、6、7步驟
- 如果項目Pods文件夾存在,則走一方法中的6、7步驟
PS: 每次pod update或者pod install都會報錯,因為Run Script的原因,所以每次添加或更新pod都得刪除Run Script更新pod再添加回Run Script(1、4、6、7步驟);這些繁瑣的操作不知道有沒有辦法避免,知道的朋友可以回復一下?不吝賜教,謝謝!
上面的解決辦法是:使用Xcode9.2創建Run Script即可。如果是Xcode 10創建就會出錯(原理不詳,估計是Xcode bug)
因為Xcode9.2創建的Run Script沒有inputFileListPaths
和outputFileListPaths
,而Xcode10創建會有,所以Xcode10創建的小朋友只需要修改project.pbxproj
文件(刪掉兩個字段相關)即可。
---------混編最新總結方法請點擊此處,建議再看完??有點自己理解再實操-------
Xcode 與 Flutter 交互
AppDelegate 改造
改造AppDelegate.h
,使其繼承FlutterAppDelegate
:
#import <Flutter/Flutter.h>
@interface AppDelegate : FlutterAppDelegate <UIApplicationDelegate, FlutterAppLifeCycleProvider>
@end
改造AppDelegate.m
:
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
{
FlutterPluginAppLifeCycleDelegate *_lifeCycleDelegate;
}
- (instancetype)init {
if (self = [super init]) {
_lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init];
}
return self;
}
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions];
}
- (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];
}
#pragma mark - Flutter
// 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];
}
}
@end
Flutter主動,Native被動 (MethodChannel)
Flutter 代碼: 引入import 'package:flutter/services.dart';
請用下面代碼替換class _MyHomePageState extends State<MyHomePage>
這個類內容
class _MyHomePageState extends State<MyHomePage> {
// 創建一個給native的channel (類似iOS的通知)
static const methodChannel = const MethodChannel('com.pages.your/native_get');
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
print('flutter的log打?。含F在輸出count=$_counter');
// 當個數累積到3的時候給客戶端發參數
if(_counter == 3) {
_toNativeSomethingAndGetInfo();
}
// 當個數累積到5的時候給客戶端發參數
if(_counter == 1002) {
Map<String, String> map = { "title": "這是一條來自flutter的參數" };
methodChannel.invokeMethod('toNativePush',map);
}
// 當個數累積到8的時候給客戶端發參數
if(_counter == 1005) {
Map<String, dynamic> map = { "content": "flutterPop回來","data":[1,2,3,4,5]};
methodChannel.invokeMethod('toNativePop',map);
}
});
}
// 給客戶端發送一些東東 , 并且拿到一些東東
Future<Null> _toNativeSomethingAndGetInfo() async {
dynamic result;
try {
result = await methodChannel.invokeMethod('toNativeSomething','大佬你點擊了$_counter下');
} on PlatformException {
result = 100000;
}
setState(() {
// 類型判斷
if (result is int) {
_counter = result;
}
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
// appBar: new AppBar(
// // Here we take the value from the MyHomePage object that was created by
// // the App.build method, and use it to set our appbar title.
// title: new Text(widget.title),
// ),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Native 代碼:
- (void)pushFlutterViewController {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
flutterViewController.navigationItem.title = @"Flutter Demo";
__weak __typeof(self) weakSelf = self;
// 要與main.dart中一致
NSString *channelName = @"com.pages.your/native_get";
FlutterMethodChannel *messageChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:flutterViewController];
[messageChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
// call.method 獲取 flutter 給回到的方法名,要匹配到 channelName 對應的多個 發送方法名,一般需要判斷區分
// call.arguments 獲取到 flutter 給到的參數,(比如跳轉到另一個頁面所需要參數)
// result 是給flutter的回調, 該回調只能使用一次
NSLog(@"flutter 給到我:\nmethod=%@ \narguments = %@",call.method,call.arguments);
if ([call.method isEqualToString:@"toNativeSomething"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"flutter回調" message:[NSString stringWithFormat:@"%@",call.arguments] delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alertView show];
// 回調給flutter
if (result) {
result(@1000);
}
} else if ([call.method isEqualToString:@"toNativePush"]) {
ThirdViewController *testVC = [[ThirdViewController alloc] init];
testVC.parames = call.arguments;
[weakSelf.navigationController pushViewController:testVC animated:YES];
} else if ([call.method isEqualToString:@"toNativePop"]) {
[weakSelf.navigationController popViewControllerAnimated:YES];
}
}];
[self.navigationController pushViewController:flutterViewController animated:YES];
}
Native主動,Flutter被動 (EventChannel)
一般用于flutter初始化需要從客戶端獲取一些參數作為渲染條件;類似iOS這邊的KVO,監聽flutter是否已經在監聽,監聽的時候回調到代理【這步其實還是flutter監聽的時候,內部發了一個通知,iOS這邊收到并回調】,iOS Native處理代理,并回調給flutter所需要參數
Flutter 代碼 (class中):
// 注冊一個通知
static const EventChannel eventChannel = const EventChannel('com.pages.your/native_post');
// 渲染前的操作,類似viewDidLoad
@override
void initState() {
super.initState();
// 監聽事件,同時發送參數12345
eventChannel.receiveBroadcastStream(12345).listen(_onEvent,onError: _onError);
}
String naviTitle = '你好,大佬' ;
// 回調事件
void _onEvent(Object event) {
setState(() {
naviTitle = event.toString();
});
}
// 錯誤返回
void _onError(Object error) {
}
Native代碼:
- (void)pushFlutterViewController_EventChannel {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
flutterViewController.navigationItem.title = @"EventChannel Demo";
// 要與main.dart中一致
NSString *channelName = @"com.pages.your/native_post";
FlutterEventChannel *evenChannal = [FlutterEventChannel eventChannelWithName:channelName binaryMessenger:flutterViewController];
// 代理
[evenChannal setStreamHandler:self];
[self.navigationController pushViewController:flutterViewController animated:YES];
}
#pragma mark - <FlutterStreamHandler>
// // 這個onListen是Flutter端開始監聽這個channel時的回調,第二個參數 EventSink是用來傳數據的載體。
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
// arguments flutter給native的參數
// 回調給flutter, 建議使用實例指向,因為該block可以使用多次
if (events) {
events(@"我是標題");
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter給native的參數
return nil;
}
交互總結
這兩種方式都差不多,一個使用的時候使用block,一個使用的時候使用delegate;最終回調給flutter的都是通過block。
MethodChannel
使用block,上下文更加明確;同一個channel name
可以根據flutter給回的call.method
、call.arguments
更加靈活的處理回調handle, 回調只能使用一次(意思就是就算你創建一個實例指向block,單block回調只能使用一次,回調之后flutter block那邊不再接收);
EventChannel
使用delegate,代碼層次更鮮明;同一個channel name
只能通過判斷arguments
參數處理回調handle, 回調可以使用多次(創建一個實例指向block,該block可以向flutter發送多次);
BasicMessageChannel
請自行學習。
疑問
創建使用FlutterViewController
Xcode的Memory一直在增加到一個水平,分類重寫- (void)dealloc
也沒有進來,估計是內存泄漏了。于是去查了官方的Issues ,確實有幾個關聯:
- Flutter SSL Memory Leaks #20409
- Unable to release FlutterViewController even when there is nothing referencing it. #21347
Native 簡單push FlutterViewController
, pop
回,內存到達一個階段后不降,FlutterViewController
不會執行dealloc
方法。不知道這誰知道有沒有解決方案?不吝賜教,謝謝!