iOS 集成 flutter
这两年比较火的混合开发的框架,那非 flutter 莫属了。根据朋友出去面试回来的反馈,好多公司现在都要求了解或者会 flutter 开发。
2020 年是特别的一年,我想更是促进了很多公司为了削减成本而选择一种混合开发的框架来开发移动端的 App。毕竟一个前端就能取代一个 Android 和一个 iOS 开发的活,肯定更能受到很多公司的追捧。刚好最近有时间,所以就看了一下 Flutter 相关的内容。
本文主要记录自己在 iOS 原生项目里对接 Flutter 内容记录。因为在整个对接的过程中,踩了一些坑,也找了不少的文章,东边借鉴一些,右边借鉴一些,终于在真机上跑起来了整个项目。
Flutter Module 集成到 iOS 的中文文档 可以参考一下,下面是自己实际对接的过程中一些主要的步骤。
iOS 项目对接 Flutter
打开 mac 的终端(Terminal)进入到你想创建项目的路径下 cd /Users/xxx/Desktop
1、创建一个 flutter module
flutter create -t module module_name
2、构建一下项目,这一步很重要。
flutter build ios --debug
3、用 Xcode 创建一个 iOS 项目。
4、将 flutter 项目和 iOS 项目放到同一个文件夹下,如下:
5、修改 Podfile 文件。(本文主要是用 CocoaPods 托管第三方)
flutter_application_path = '../job'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
install_all_flutter_pods(flutter_application_path)
如下:
6、安装第三方的内容
pod install
7、修改 Appdelegate 文件
// 修改.h 文件
#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>
@interface AppDelegate : FlutterAppDelegate
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@property(nonatomic, strong) FlutterViewController *vc;
@property(nonatomic, strong) FlutterMethodChannel *batteryChannel;
@end
// 修改.m 文件
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"io.flutter"];
[self.flutterEngine run];
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
self.window.rootViewController = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
self.vc = (FlutterViewController *)self.window.rootViewController;
self.batteryChannel = [FlutterMethodChannel methodChannelWithName:@"BBBBBBB" binaryMessenger:self.vc.binaryMessenger];
__weak typeof(self) weakSelf = self;
[self.batteryChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
//flutter 和 iOS 交互, AAAAA flutter 里 methodChannel invoke 的方法的名称
if ([call.method isEqualToString:@"AAAAA"]) {
//todo 做一些原生上的操作,比较调用原生的界面啥的
// iOS 传值给 flutter
result(@"SSSSSS");
} else {
result(FlutterMethodNotImplemented);
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (void)changeRootVC {
self.window.rootViewController = self.vc;
}
@end
Flutter 里调用 iOS 的写法
1、在 flutter 里定义一下 _methodChannel
// 和上面的 iOS 初始化 FlutterMethodChannel 要一致
static const _methodChannel = MethodChannel('BBBBBBB');
2、定义一下方法
static Future<String> iosVideo() async {
return await _methodChannel.invokeMethod('video');
}
3、在需要的地方调用一下就行
注意
1、在修改了 flutter 内容之后,调用 iOS 集成 flutter 里的第 2 步,重新构建一下。
2、网上很多说要在 iOS 项目里配置 config 文件,但是在新的 flutter 里,已经不需要了。
3、也不需要在 iOS 项目里配置 run script 了。
4、pod install 之后,build 一下iOS 项目之后,再修改 Appdelegate 文件,不然没有 flutter.framework 和 app.framework