环境配置
因为是在iOS已有项目中集成Flutter,所以正常情况的环境是macOS + Xcode + flutter环境;再加上flutter 需要的的dart语言编辑器 Android Studio 、IntelliJ IDEA 或 Visual Studio Code (VS Code) ;因为flutter是多平台,所以也要安装安卓相关的SDK。macOS下搭建Flutter开发环境可以参考 Mac下搭建Flutter开发环境。
创建Flutter项目
Flutter项目最好独立于iOS项目,不要耦合进iOS项目中,最好放在与项目目录同级。
在iOS项目目录下终端运行:
flutter create -t module flutter_module
运行完成后,iOS项目与Flutter项目层级如下:
iOS工程配置
-
因为Flutter混合开发还不支持bit code,所以在iOS工程中需要关闭bit code。
-
创建Xcode项目中的Config文件,引向flutter module
新建Config目录,管理Xcode工程的配置衔接文件,分别创建 Flutter.xcconfig 、Debug.xcconfig、Release.xcconfig 三个配置文件;其中Flutter.xcconfig 是指向外目录flutter module的Generated.xcconfig 文件路径引用文件,其他两个代表Xcode的环境配置文件。
三个文件的引入内容 (所引用的都是绝对路径,最终都是指引到 Generated.xcconfig)
Flutter.xcconfig:
#include "../../flutter_module/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
Debug.xcconfig:
#include "Flutter.xcconfig"
Release.xcconfig:
#include "Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
-
修改Xcode project环境配置
最重要: 引入xcode-backend.sh
在iOS工程里添加运行脚本 "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build,并且确保Run Script这一行在"Target dependencies" 或者 "Check Pods Manifest.lock"后面。
点击Xcode运行,会执行到xcode-backend.sh脚本;如果运行成功,则说明环境配置的都没问题,此时在Flutter工程下的.ios/Flutter/目录下会生成App.framework和/engine/Flutter.framework,其中App.framework即为Flutter工程生成的产物。
打包framework命令
flutter build ios-framework --output=/Users/Desktop/FlutterTest
导入Flutter工程产物到iOS工程中
方法一:可以将Flutter工程中生成的App.framework和Flutter.framework产物拷贝到iOS工程中,然后再链接到iOS项目中。
该方法存在的问题:每次修改完Flutter代码重新打包生成App.framework产物后都需要重新拷贝到iOS工程中。
方法二:直接让iOS项目链接Flutter工程下的App.framework和Flutter.framework产物,然后修改导入framework的路径,这样修改Flutter的代码后通过运行Xcode即可得到最新Flutter工程的产物。
导入App.framework和Flutter.framework后需要将Embed改成Embed & Sign。
至此,Xcode与Flutter之间混编配置完成,两个项目文件已经关联上了。这时候你就可以修改main.dart 文件内容,重新编译运行Xcode 则APP.framework自动会被编译成最新的flutter代码。
下面开始写代码了
从iOS页面跳转到Flutter页面
- 将Flutter工程下的main.dart替换成下面的代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "My App",
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text("My App"),
),
body: Center(
child: Text("Hello World!"),
),
),
);
}
}
- iOS工程点击屏幕跳转到Flutter页面:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
FlutterViewController *flutterVC = [[FlutterViewController alloc] init];
flutterVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:flutterVC animated:YES completion:nil];
}
- 点击Xcode运行,点击屏幕就可以跳转到Flutter页面,效果图如下:
iOS原生与Flutter进行交互
-
Flutter调用iOS的方法,iOS返回结果给Flutter:
main.dart代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyHome());
}
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "My Home",
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State <MyHomePage> {
// 创建一个给native的channel(类似于iOS的通知)
static const methodChannel = const MethodChannel('com.pages.your/native_get');
var _leftNumber = 10;
var _rightNumber = 20;
var _result = 0;
Future<Null>_callNativeMethodToCalculateAdd() async {
dynamic result;
try {
// Flutter调用Native
result = await methodChannel.invokeMethod('callAdd', {"left": _leftNumber, "right": _rightNumber});
} on PlatformException {
result = 0;
}
setState(() {
_result = result;
});
}
Future<Null>_callNativeMethodToCalculateMul() async {
dynamic result;
try {
// Flutter调用Native
result = await methodChannel.invokeMethod('callMul', {"left": _leftNumber, "right": _rightNumber});
} on PlatformException {
result = 0;
}
setState(() {
_result = result;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('My Home'),
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: GestureDetector(
child: Text("调用native方法计算加法"),
onTap: () {
_callNativeMethodToCalculateAdd();
},
),
color: Colors.grey,
margin: EdgeInsets.only(bottom: 20),
),
Container(
child: GestureDetector(
child: Text("调用native方法计算乘法"),
onTap: () {
_callNativeMethodToCalculateMul();
},
),
color: Colors.grey,
margin: EdgeInsets.only(bottom: 20),
),
Container(
child: Text("计算结果是: ${_result}"),
)
],
),
),
);
}
}
iOS代码:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
FlutterViewController *flutterVC = [[FlutterViewController alloc] init];
flutterVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:flutterVC animated:YES completion:nil];
// 要与main.dart中一致
NSString *channelName = @"com.pages.your/native_get";
FlutterMethodChannel *messageChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:flutterVC];
[messageChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
NSDictionary *numbers = call.arguments;
NSInteger left = [numbers[@"left"] integerValue];
NSInteger right = [numbers[@"right"] integerValue];
NSInteger r = 0;
if ([call.method isEqualToString:@"callAdd"]) {
r = left + right;
} else if ([call.method isEqualToString:@"callMul"]) {
r = left * right;
}
result(@(r));
}];
}
运行结果:
- iOS主动调用Flutter
一般用于flutter初始化需要从客户端获取一些参数作为渲染条件;类似iOS这边的KVO,监听flutter是否已经在监听,监听的时候回调到代理[这步其实还是flutter监听的时候,内部发了一个通知,iOS这边收到并回调,iOS Native处理代理,并回调给flutter所需要参数]
main.dart代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyHome());
}
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "My Home",
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// 注册一个通知
static const EventChannel eventChannel = const EventChannel("com.pages.your/native_post");
// 渲染前的操作,类似于iOS中的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) {
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My Home"),
),
body: Center(
child: Text(naviTitle),
),
);
}
}
iOS代码:
#import "ViewController.h"
#import <Flutter/Flutter.h>
@interface ViewController () <FlutterStreamHandler>
{
int I;
FlutterEventSink _events;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
}
- (void)timerRun {
if (_events) {
_events(@(i++));
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
FlutterViewController *flutterVC = [[FlutterViewController alloc] init];
flutterVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:flutterVC animated:YES completion:nil];
// 要与main.dart中一致
NSString *channelName = @"com.pages.your/native_post";
FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:channelName binaryMessenger:flutterVC];
[eventChannel setStreamHandler:self];
}
#pragma mark - FlutterStreamHandler
// 这个onListen是Flutter端开始监听这个channel时的回调,第二个参数EventSink是用来传数据的载体
- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
// arguments 是 flutter给native的参数
// 回调给flutter,建议使用实例指向,因为该block可以使用多次
_events = events;
return nil;
}
// flutter不在接收
- (FlutterError *)onCancelWithArguments:(id)arguments {
// arguments flutter给native的参数
return nil;
}
@end
运行结果:
交互总结
这两种方式都差不多,一个使用的是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发送多次);
参考
iOS Native混编Flutter交互实践
iOS老项目集成Flutter(iOS混编Flutter)
Flutter官方文档
Flutter中文网