一:我们先来看看flutter应用的启动流程
flutter应用的启动流程在流程图里我们看到,应用启动先执行ios原生平台的main函数
,之后才会执行flutter平台的main函数
。
ios
应用启动后,会在ios原生平台的main()函数
的代理方法里创建一个 FlutterViewController
,并将 window
的根页面设置为 FlutterViewController
。这个FlutterViewController
会隐式的创建一个FlutterEngine(flutter引擎)
。
flutter引擎实例对象
一旦运行,就会执行 flutter中的main()函数
。
注意
:在ios平台,我们写代码时要尽量保持FlutterEngine
的复用,保证只有一个FlutterEngine
对象,因为多个flutter
引擎会导致flutter
的main()
方法执行多次;
而我们知道主函数main()
都是在整个应用程序生命周期中只执行一次的,主函数执行多次会导致不可预知的逻辑错误。
二:flutter主动调用ios方法,ios方法被动响应。
1:首先:我们需要在ios
应用启动的代理方法- (void)applicationDidFinishLaunching:(UIApplication *)application
里注册对flutter
平台的监听:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
//第一步:初始化ios调用flutter,用于ios平台主动调用flutter方法
[[FlutterEvent sharedInstance] setUp];
//第二步:初始化flutter调用ios,用于监听flutter传递过来的消息
[[FlutterMethod sharedInstance] setUp];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
FlutterMethod.m 文件中, setUp()
方法的实现
#import "FlutterMethod.h"
#import "FlutterMethodKey.h"
#import <Flutter/Flutter.h>
#import "AppDelegate.h"
// 通讯key
#define Key_deliver_methodChannel @"com.deliver.method"
/** 注册远程推送 */
#define Key_RegisterRemotePush @"register_remote_push";
/** 获取App信息 */
#define Key_GetAppInfo @"get_appInfo";
@implementation FlutterMethod
static FlutterMethod* singleInstance = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if(nil == singleInstance) {
singleInstance = [super allocWithZone:zone];
}
return singleInstance;
}
+ (FlutterMethod *)sharedInstance {
if(nil == singleInstance) {
singleInstance = [[FlutterMethod alloc] init];
}
return singleInstance;
}
- (void)setUp {
//直接获取根页面FlutterViewController;再获取到FlutterEngine。
FlutterViewController* flutterVC = (FlutterViewController*) [UIApplication sharedApplication].delegate.window.rootViewController;
id binarymessenger = flutterVC.engine.binaryMessenger;
FlutterMethodChannel* methodChannel = [FlutterMethodChannel methodChannelWithName:Key_deliver_methodChannel binaryMessenger:binarymessenger];
__weak typeof(self) weakSelf = self;
[methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
NSLog(@"flutter传给ios的参数:%@",call.arguments);
if([Key_RegisterRemotePush isEqualToString:call.method]) {
//开始注册推送...
[AppDelegate beginRegisterRemotePush];
result(nil);
}else if([Key_GetAppInfo isEqualToString:call.method]) {
//获取应用信息
NSString* appInfo = [weakSelf getAppInfo];
result(appInfo);
}
}];
}
end
2:然后,在flutter
平台需要调用ios
原生方法时可以这样写:
void registerRemotePush() async {
if(Platform.isIOS) {
//注册推送功能,ios使用原生平台推送
dynamic response = await FlutterMethodChannel.flutterCallNativeMethod(FlutterMethodKey.Key_RegisterRemotePush, {"data":"传点什么参数好呢???"});
print("ios回传的参数:$response");
}else if(Platform.isAndroid) {
}
}
FlutterMethodChannel类的封装:
import 'dart:convert';
import 'package:flutter/services.dart';
/**
* flutter 主动调用原生平台方法
* */
class FlutterMethodKey {
/// flutter调用(ios/android)方法,一个Key对应一个方法。
static const Key_RegisterRemotePush = "register_remote_push";/** 注册远程推送 */
static const Key_GetAppInfo = "get_appInfo";/** 获取App信息 */
}
class FlutterMethodChannel {
static const _Key_MethodChannel = "com.deliver.method";
static const _platform = const MethodChannel(_Key_MethodChannel);
// flutter调用原生
static Future<dynamic> flutterCallNativeMethod(String methodKey, dynamic params) async {
if(null==params){params = "";}
print('flutter调用原生:$methodKey');
print('flutter传给原生参数:$params');
try {
var result = await _platform.invokeMethod(methodKey,params);
return result;
}on PlatformException catch (e) {
print("flutter调用原生平台方法出错:${e.message}");
return e;
}
}
}
三: ios主动调用flutter方法,flutter被动响应
1:首先:我们需要在 flutter
应用启动的 main.dart
文件里注册对ios
原生平台的监听:
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
//注册原生调用flutter的监听
FlutterEventChannel.registerEventChannel();
}
}
FlutterEventChannel类的封装:
import 'dart:convert';
import 'package:flutter/services.dart';
/**
* 原生平台方法调用 flutter 都会触发这里的回调。
* */
class FlutterEventKey {
///(ios/android)调用flutter方法,一个Key对应一个方法。
static const Key_ReceivePushToken = "receive_push_token";/** 获取到了推送token */
}
class FlutterEventChannel {
static const _Key_EventChannel = "com.deliver.event";
static const EventChannel _eventChannel = const EventChannel(_Key_EventChannel);
///注册(ios/android)调用flutter的事件回调
static void registerEventChannel() {
_eventChannel.receiveBroadcastStream().listen(
_onNativeCallFlutterEvent,
onError: _onNativeCallFlutterError,
);
}
///如果原生平台调用 flutter,下面的这个方法就会被触发执行。
static void _onNativeCallFlutterEvent(dynamic event) {
print("native平台给flutter传参数啦:$event");
if(event is String) {
var eventObject = json.decode(event);
if(eventObject is Map) {
var data = eventObject["data"];
String method = eventObject["method"];
if(method == FlutterEventKey.Key_ReceivePushToken) {
_savePushTokenToLocalDevice(data);
}
}
}
}
///如果调用 flutter 出错了,下面的这个方法就会执行。
static void _onNativeCallFlutterError(Object error) {
}
//***** 10101010101010101010101010101010101010101010101010101010101010101010101010101010 *****//
static void _savePushTokenToLocalDevice(String pushToken) {
//将获取到的推送token保存到本地
// save()...
}
}
2:然后、在ios
需要调用flutter
的时候,我们可以这么写:
#define Key_ReceivePushToken @''receive_push_token" // 和flutter端 保持一致。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//获取token
NSString *token=@"获取token"
NSLog(@"苹果apns推送获取token成功:%@",token);
[[FlutterEvent sharedInstance] platformCallFlutter:Key_ReceivePushToken data:token];
}
FlutterEvent.m文件中, - (void)platformCallFlutter:(NSString*)methodKey data:(NSObject*)value
方法的实现
#import "FlutterEvent.h"
#import <Flutter/Flutter.h>
#define Key_deliver_eventChannel @"com.deliver.event"
@interface FlutterEvent()<FlutterStreamHandler>
@property(nonatomic,strong)FlutterEventSink eventSink;;
@end
@implementation FlutterEvent
static FlutterEvent* singleInstance = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if(nil == singleInstance) {
singleInstance = [super allocWithZone:zone];
}
return singleInstance;
}
+ (FlutterEvent *)sharedInstance {
if(nil == singleInstance) {
singleInstance = [[FlutterEvent alloc] init];
}
return singleInstance;
}
- (void)setUp {
FlutterViewController* flutterVC = (FlutterViewController*) [UIApplication sharedApplication].delegate.window.rootViewController;
id binarymessenger = flutterVC.engine.binaryMessenger;
FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:Key_deliver_eventChannel binaryMessenger:(NSObject<FlutterBinaryMessenger> *)binarymessenger];
[eventChannel setStreamHandler:self];
}
- (void)platformCallFlutter:(NSString *)methodKey data:(NSObject *)value {
if(nil == methodKey) {
return;
}
NSDictionary* dataDic = @{@"method":methodKey,@"data":value};
NSData* data = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
NSString* jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(self.eventSink) {
self.eventSink(jsonStr);
}
}
#pragma mark - FlutterStreamHandler
- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
self.eventSink = events;
return nil;
}
- (FlutterError *)onCancelWithArguments:(id)arguments {
NSLog(@"flutter给ios的参数(arguments):%@",arguments);
return nil;
}
@end
网友评论