iOS 原生与Flutter混编
前言
Flutter是一款移动应用程序SDK,一份代码可以同时生成iOS和Android两个高性能应用程序能提高开发效率,在应用程序运行时更改代码并重新加载,提供的丰富的Material Design(Android)和Cupertino(iOS风格)等优点。看到此处我们是不是很想加入flutter开发中呢?但是目前 flutter 框架还比较新,有些功能还是需要原生去实现,那我们该怎样选择呢?下面带你进入混编之旅。
准备工作
1.混编的前提是你的电脑必须有 flutter 环境,可以参考Flutter中文网。
2.一个Xcode项目。
3.三方管理平台CocoaPods。
创建flutter模块
因为使用flutter模块需要跨平台,所以需要在项目根目录创建一个和项目目录平级的模块,比如项目目录是some/path/MyApp,那么你需要在some/path目录项创建flutter模块。
cd some/path
flutter create -t module my_flutter
依赖引入
我们开发中大多使用CocoaPods管理第三方和依赖。在项目中引入flutter模块,就需要引入flutter依赖库。在pod配置文件中加入以下代码,然后执行pod install。
flutter_application_path = '../my_flutter/'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
这时我们的flutter模块以及依赖环境已经全部配置好了。我们想用iOS项目去调用flutter还是做不到,需要在Xcode里面配置一些信息。
Xcode配置
flutter和iOS混合开发是不支持BitCode的,所以我们需要把它设置为NO。
屏幕快照 2019-07-05 15.51.46.png
在iOS工程里面添加运行脚本
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
修改项目代码
1.将AppDelegate的头文件改成
#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>
@interface AppDelegate : FlutterAppDelegate
@property (strong, nonatomic) UIWindow *window;
@end
2.在AppDelegate的实现文件的didFinishLaunchingWithOptions方法中添加
[GeneratedPluginRegistrant registerWithRegistry:self];
综上所述flutter模块已经集成到我们iOS项目中了,代码运行也没有问题,那我们怎样才能在iOS中调用flutter界面呢?怎样让他们进行交互呢?
#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];
//此处是设置路由跳转的
[flutterViewController setInitialRoute:@"myApp"];
[self presentViewController:flutterViewController animated:false completion:nil];
}
@end
在flutter中怎样才能响应这个调用呢?
switch (route) {
case 'myApp':
return new MyApp();
default:
return Center(
child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
);
这样就可以从iOS原生跳转到flutter界面了,运行APP点击按钮就会出现下面的界面。
屏幕快照 2019-07-05 16.37.04.png
这种界面肯定不符合我们开发的需求,iOS原生和flutter都有一个导航栏,那我们就需要隐藏一个。
隐藏iOS原生导航
[self.navigationController setNavigationBarHidden:YES animated:NO];
但是使用flutter的导航,点击返回的时候比较麻烦,需要监听flutter点击事件,在调用iOS原生的返回,代码处理在下方。
隐藏flutter导航
将图中选中的部分删除
运行之后界面清爽多了,但是还有一个DEBUG标志,可以使用一下代码去掉
debugShowCheckedModeBanner: false, // 去除debug旗标
iOS与flutter的数据传输怎么做呢?代码参考
// 创建FlutterViewController,并跳转到Flutter页面
FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
// 设置路由名字 跳转到不同的flutter界面
[flutterViewController setInitialRoute:@"myApp"];
__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 方法名
// call.arguments 获取到 flutter 给到的参数
// result 是给flutter的回调, 该回调只能使用一次
NSLog(@"method=%@ \narguments = %@", call.method, call.arguments);
if ([call.method isEqualToString:@"iOSFlutter"]) {
//如果隐藏iOS原生方法,需要做f返回处理
[self.navigationController popViewControllerAnimated:YES];
}
// flutter传参给iOS
if ([call.method isEqualToString:@"iOSFlutter1"]) {
NSDictionary *dic = call.arguments;
NSLog(@"arguments = %@", dic);
}
// iOS给flutter返回值
if ([call.method isEqualToString:@"iOSFlutter2"]) {
if (result) {
result(@"返回给flutter的内容");
}
}
}];
[self.navigationController pushViewController:flutterViewController animated:YES];
在flutter中的代码
import 'dart:ui' as ui; // 调用window拿到route判断跳转哪个界面
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
//import 'package:flutter_module/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 MyApp();
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',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
routes: <String, WidgetBuilder>{
"/home":(BuildContext context) => new MyApp(),
},
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界面时候iOS传值给flutter呢?
#import "TargetViewController.h"
#import <Flutter/Flutter.h>
@interface TargetViewController () <FlutterStreamHandler>
@end
@implementation TargetViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"TargetViewController";
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)pushFlutterViewController_EventChannel {
FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
flutterViewController.navigationItem.title = @"Demo";
[flutterViewController setInitialRoute:@"home"];
// 要与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;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self pushFlutterViewController_EventChannel];
}
@end
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class HomePage extends StatefulWidget {
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// 注册一个通知
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 = 'title' ;
// 回调事件
void _onEvent(Object event) {
setState(() {
naviTitle = event.toString();
});
}
// 错误返回
void _onError(Object error) {
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Material(
child: new Scaffold(
body: new Center(
child: new Text(naviTitle),
),
),
),
);
}
}