前提
前提是你已经配置好flutter环境了,如果没有配置好,可以参考我上一篇文章,先把环境配好.查看是否已经配好环境,在终端输入命令: flutter doctor
一,项目准备
1. 先拿出你已有的iOS项目
2. 打开终端cd 到你的项目路径
3. 创建module (flutter 模块),输入以下命令
flutter_library是flutter模块的名字,可以自己命名,最好带有flutter字样,这样好区分,命令执行完之后,就会生成一个flutter_library文件夹,这文件夹就是你将来写flutter代码的地方
flutter create -t module flutter_library
如图:
WeChat2ea5948994b8559845ff499d75acfd07.png
在这个文件夹里面有个配置文件很重要在隐藏文件.iOS中,先留意一下,待会有用,如图:
WeChatac214b2cda7e747f8a4fef770056b960.png
4. 创建三个配置文件,Flutter文件夹是自己创建的,你可以自己想一个其他名字,Flutter.xcconfig, Debug.xcconfig,Release.xcconfig,创建方法如图:
WeChatadc0ddc91ba5f240e79a3c3322ff4868.png在Flutter.xcconfig文件中写入:
#include "../flutter_library/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
在Debug.xcconfig文件中写入
#include "../Flutter/Flutter.xcconfig"
// 如果项目中引入pods可以不加以下代码
#include "Pods/Target Support Files/Pods-FlutterMixed/Pods-FlutterMixed.debug.xcconfig"
在Release.xconfig文件中写入
#include "../Flutter/Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
// 如果项目中引入pods可以不加以下代码
#include "Pods/Target Support Files/Pods-FlutterMixed/Pods-FlutterMixed.debug.xcconfig"
5. Xcode project环境配置(如图)
WeChat57bd2851bdfd8c24caeccdf83a7836fe.png第四步和第五步的目的是让iOS项目与flutter模块关联上.
6. 添加脚本(如图)
WeChatdf2579ac418ebfc9a7c232310b0b20ae.png脚本代码是:
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
WeChat2a3fe2c31153c52ef68027309fb2181b.png进展到这一步,run一下项目正常来说,在你的Flutter文件夹中会新出来几个文件,如果项目编译通过之后,并没有出现新的文件,你可以找到你配置环境的时候下载的flutter文件,找到这个文件(如图)
打开它找到如下代码,再注释掉,再重新run,build也行
if [[ -e "${project_path}/.ios" ]]; then
derived_dir="${project_path}/.ios/Flutter"
fi
这时候,新生成的文件就会出来了,如图:
WeChate35219153ae3e6eb7fe5360f0178d603.png
也许你会纳闷,为啥其他很多博客上写着,还会出来flutter_assets这个文件夹,还教你如何导入项目,说实话,为了这事我折腾了两天,也搞不懂,我这里为啥没有出来,如果哪位大牛知道,欢迎赐教,尽管没有出来flutter_assets这个文件,但是后来我发现并不影响我后面的步骤.
7. 把App.framework和engin引入到xcode中
这时候,就可以在你的iOS旧项目中引入#import <Flutter/Flutter.h>不会报错了.
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:@"跳转到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>
// // 这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体。
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
// arguments flutter给native的参数
// 回调给flutter, 建议使用实例指向,因为该block可以使用多次
if (events) {
events(@"push传值给flutter的vc");
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter给native的参数
NSLog(@"%@", arguments);
return nil;
}
@end
在flutter中main.dart代码如下
import 'dart:ui' as ui; // 调用window拿到route判断跳转哪个界面
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './pages/HomePage.dart';
void main() => runApp(_widgetForRoute(ui.window.defaultRouteName));
// 根据iOS端传来的route跳转不同界面
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> {
// 创建一个给native的channel (类似iOS的通知)
static const methodChannel = const MethodChannel('com.pages.your/native_get');
_iOSPushToVC() async {
await methodChannel.invokeMethod('iOSFlutter', '参数');
}
_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("跳转ios新界面,参数是字符串")),
new FlatButton(onPressed: () {
_iOSPushToVC1();
}, child: new Text("传参,参数是map,看log")),
new FlatButton(onPressed: () {
_iOSPushToVC2();
}, child: new Text("接收客户端相关内容")),
],
),
),
);
}
}
这个时候,点击按钮,就能跳转到flutter的页面
9. 热更新
- cd到 flutter模块目录, 输入flutter attach命令
- 打开xcode,运行,之后就可以正常热更新
网友评论