2019年初的时候,我学过一阵子Flutter,着重看了下Bloc(business logic component),自己写了个小demo。完了之后,Flutter就被抛之脑后了。
话不多说,直接开整,参考了官网的关于编写跨平台代码文档:传送门
其实基本思路很简单,两步
一.Flutter 传递消息给原生,说我要去原生界面
二.在原生AppDelegate.m里,将FlutterViewController 作为rootViewController,然后放在Navigation Stack里。当原生接收到消息,实现跳转功能,完事!
话不多说,Let's dive in.
第一步,Flutter 怎么将消息传递到原生端呢?
1.创建一个通信的频道
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
...
class _MyHomePageState extends State<MyHomePage> {
static const platform = const MethodChannel('samples.flutter.dev/goToNativePage');
}
2.实现Trigger Function
Future<void> _goToNativePage() async {
try {
final int result = await platform
.invokeMethod('goToNativePage', {'test': 'from flutter'});
print(result);
} on PlatformException catch (e) {}
}
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RaisedButton(
child: Text('去原生界面'),
onPressed: _goToNativePage,
color: Colors.blueAccent,
textColor: Colors.white,
),
Text(
"Flutter 页面",
style: new TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w900,
fontFamily: "Georgia",
),
)
],
),
),
);
}
添加一个按钮,给这按钮再添加一个_goToNativePage方法,在这里如果还要传递参数的话,直接像这样写就ok了
platform.invokeMethod('goToNativePage', {'key': 'value'});
第二步 ,原生接收消息并实现跳转
因为你导航到新界面,所以需要引入UINavigationController
在AppDelegate.m里,@implementation AppDelegate
上方添加代码
@interface AppDelegate()
@property (nonatomic, strong) UINavigationController *navigationController;
@end
1.将FlutterView设为根视图
FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
2.嵌入导航堆栈里
self.navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = self.navigationController;
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self.window makeKeyAndVisible];
3.Flutter和原生通信的接口的实现
FlutterMethodChannel* testChannel =
[
FlutterMethodChannel methodChannelWithName:@"samples.flutter.dev/goToNativePage"
binaryMessenger:controller
];
[testChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
NSLog(@"%@", call.method);
//接收从flutter传递过来的参数
NSLog(@"%@", call.arguments[@"test"]);
if ([@"goToNativePage" isEqualToString:call.method]) {
//实现跳转的代码
} else {
result(FlutterMethodNotImplemented);
}
}];
想获取从flutter传递过来的参数, call.arguments[@"key"]
,用这段代码
4.实现跳转到原生界面
到了这,就相当简单了,补全跳转代码
NSString * storyboardName = @"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"NativeViewController"];
vc.navigationItem.title = call.arguments[@"test"];
[self.navigationController pushViewController:vc animated:true];
gayhub 项目地址:传送门
IOS Swift版本:传送门
到了这里,功能就实现了。如果有更好方式,请告诉我.