前提
前提是你已經(jīng)配置好flutter環(huán)境了,如果沒有配置好,可以參考我上一篇文章,先把環(huán)境配好.查看是否已經(jīng)配好環(huán)境,在終端輸入命令: flutter doctor
一,項(xiàng)目準(zhǔn)備
1. 先拿出你已有的iOS項(xiàng)目
2. 打開終端cd 到你的項(xiàng)目路徑
3. 創(chuàng)建module (flutter 模塊),輸入以下命令
flutter_library是flutter模塊的名字,可以自己命名,最好帶有flutter字樣,這樣好區(qū)分,命令執(zhí)行完之后,就會生成一個(gè)flutter_library文件夾,這文件夾就是你將來寫flutter代碼的地方
flutter create -t module flutter_library
如圖:
在這個(gè)文件夾里面有個(gè)配置文件很重要在隱藏文件.iOS中,先留意一下,待會有用,如圖:
4. 創(chuàng)建三個(gè)配置文件,Flutter文件夾是自己創(chuàng)建的,你可以自己想一個(gè)其他名字,Flutter.xcconfig, Debug.xcconfig,Release.xcconfig,創(chuàng)建方法如圖:
在Flutter.xcconfig文件中寫入:
#include "../flutter_library/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
在Debug.xcconfig文件中寫入
#include "../Flutter/Flutter.xcconfig"
// 如果項(xiàng)目中引入pods可以不加以下代碼
#include "Pods/Target Support Files/Pods-FlutterMixed/Pods-FlutterMixed.debug.xcconfig"
在Release.xconfig文件中寫入
#include "../Flutter/Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
// 如果項(xiàng)目中引入pods可以不加以下代碼
#include "Pods/Target Support Files/Pods-FlutterMixed/Pods-FlutterMixed.debug.xcconfig"
5. Xcode project環(huán)境配置(如圖)
第四步和第五步的目的是讓iOS項(xiàng)目與flutter模塊關(guān)聯(lián)上.
6. 添加腳本(如圖)
腳本代碼是:
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
進(jìn)展到這一步,run一下項(xiàng)目正常來說,在你的Flutter文件夾中會新出來幾個(gè)文件,如果項(xiàng)目編譯通過之后,并沒有出現(xiàn)新的文件,你可以找到你配置環(huán)境的時(shí)候下載的flutter文件,找到這個(gè)文件(如圖)
打開它找到如下代碼,再注釋掉,再重新run,build也行
if [[ -e "${project_path}/.ios" ]]; then
derived_dir="${project_path}/.ios/Flutter"
fi
這時(shí)候,新生成的文件就會出來了,如圖:
也許你會納悶,為啥其他很多博客上寫著,還會出來flutter_assets這個(gè)文件夾,還教你如何導(dǎo)入項(xiàng)目,說實(shí)話,為了這事我折騰了兩天,也搞不懂,我這里為啥沒有出來,如果哪位大牛知道,歡迎賜教,盡管沒有出來flutter_assets這個(gè)文件,但是后來我發(fā)現(xiàn)并不影響我后面的步驟.
7. 把App.framework和engin引入到xcode中
這時(shí)候,就可以在你的iOS舊項(xiàng)目中引入#import <Flutter/Flutter.h>不會報(bào)錯(cuò)了.
8. 上代碼
iOS ViewController中代碼如下
#import <Flutter/Flutter.h>
@interface SpaceBookingViewController ()<FlutterStreamHandler>
@end
@implementation SpaceBookingViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initNavigationView];
[self initSubView];
}
- (void)initNavigationView{
self.navigationItem.title = @"flutter測試";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"跳轉(zhuǎn)到flutter" style:UIBarButtonItemStylePlain target:self action:@selector(onRightItemClickAction)];
}
- (void)initSubView{
[self.view addSubview:self.tableView];
[self.view addSubview:self.titleView];
}
- (void)onRightItemClickAction{
[self pushFlutterViewController_EventChannel];
}
- (void)pushFlutterViewController_EventChannel {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
[flutterViewController.view setBackgroundColor:[UIColor whiteColor]];
flutterViewController.navigationItem.title = @"Demo";
[flutterViewController setInitialRoute:@"myApp"];
// 要與main.dart中一致
NSString *channelName = @"com.pages.your/native_post";
FlutterEventChannel *evenChannal = [FlutterEventChannel eventChannelWithName:channelName binaryMessenger:flutterViewController];
// 代理FlutterStreamHandler
[evenChannal setStreamHandler:self];
[self.navigationController pushViewController:flutterViewController animated:YES];
}
#pragma mark - <FlutterStreamHandler>
// // 這個(gè)onListen是Flutter端開始監(jiān)聽這個(gè)channel時(shí)的回調(diào),第二個(gè)參數(shù) EventSink是用來傳數(shù)據(jù)的載體。
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
// arguments flutter給native的參數(shù)
// 回調(diào)給flutter潜秋, 建議使用實(shí)例指向捆昏,因?yàn)樵揵lock可以使用多次
if (events) {
events(@"push傳值給flutter的vc");
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter給native的參數(shù)
NSLog(@"%@", arguments);
return nil;
}
@end
在flutter中main.dart代碼如下
import 'dart:ui' as ui; // 調(diào)用window拿到route判斷跳轉(zhuǎn)哪個(gè)界面
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './pages/HomePage.dart';
void main() => runApp(_widgetForRoute(ui.window.defaultRouteName));
// 根據(jù)iOS端傳來的route跳轉(zhuǎn)不同界面
Widget _widgetForRoute(String route) {
switch (route) {
case 'myApp':
return new MyApp();
case 'home':
return new homepage();
default:
return Center(
child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
);
}
}
class MyApp extends StatelessWidget {
Widget _home(BuildContext context) {
return new MyHomePage(title: 'Flutter Demo Home Page');
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner:false,
theme: new ThemeData(
primarySwatch: Colors.blue,
),
routes: <String, WidgetBuilder>{
"/home":(BuildContext context) => new homepage(),
},
home: _home(context),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// 創(chuàng)建一個(gè)給native的channel (類似iOS的通知)
static const methodChannel = const MethodChannel('com.pages.your/native_get');
_iOSPushToVC() async {
await methodChannel.invokeMethod('iOSFlutter', '參數(shù)');
}
_iOSPushToVC1() async {
Map<String, dynamic> map = {"code": "200", "data":[1,2,3]};
await methodChannel.invokeMethod('iOSFlutter1', map);
}
_iOSPushToVC2() async {
dynamic result;
try {
result = await methodChannel.invokeMethod('iOSFlutter2');
} on PlatformException {
result = "error";
}
if (result is String) {
print(result);
showModalBottomSheet(context: context, builder: (BuildContext context) {
return new Container(
child: new Center(
child: new Text(result, style: new TextStyle(color: Colors.brown), textAlign: TextAlign.center,),
),
height: 40.0,
);
});
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FlatButton(onPressed: () {
_iOSPushToVC();
}, child: new Text("跳轉(zhuǎn)ios新界面究驴,參數(shù)是字符串")),
new FlatButton(onPressed: () {
_iOSPushToVC1();
}, child: new Text("傳參吹艇,參數(shù)是map诱建,看log")),
new FlatButton(onPressed: () {
_iOSPushToVC2();
}, child: new Text("接收客戶端相關(guān)內(nèi)容")),
],
),
),
);
}
}
這個(gè)時(shí)候,點(diǎn)擊按鈕,就能跳轉(zhuǎn)到flutter的頁面
9. 熱更新
- cd到 flutter模塊目錄, 輸入flutter attach命令
- 打開xcode,運(yùn)行,之后就可以正常熱更新