提到flutter 与 原生工程混编,网上找到的资料大多都是介绍, 原生工程怎么去集成flutter,而对于flutter工程怎么去集成原生工程的介绍,少之又少,即使有介绍,质量也不理想,于是产生了写这篇文章的动力. 原生工程怎么去集成flutter, 官方有提供出了方案, 还有闲鱼团队,比较成熟的第三方集成方案,这个小伙伴们自己去探索一下喽.
回到正题,我们将要探讨的是,flutter工程怎么去集成原生工程,下面将会以iOS为例.先上最终效果图吧
flutter层
main文件下代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
static const platform =
const MethodChannel('samples.flutter.dev/goToNativePage');
Future _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: Scaffold(
appBar: AppBar(
title: Text("flutter title"),
),
body: 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",
),
)
],
),
),
),
);
}
}
关键的代码就是调用MethodChannel相关方法,与原生进行沟通.
static const platform =
const MethodChannel('samples.flutter.dev/goToNativePage');
Future _goToNativePage() async {
try {
final int result = await platform
.invokeMethod('goToNativePage', {'test': 'from flutter'});
print(result);
} on PlatformException catch (e) {}
}
原生层(也就是iOS工程里面)
在AppDelegate.m增加以下代码
FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
// 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];
FlutterMethodChannel* testChannel = [FlutterMethodChannel methodChannelWithName:@"samples.flutter.dev/goToNativePage" binaryMessenger:controller.binaryMessenger
];
[testChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
NSLog(@"%@", call.method);
//接收从flutter传递过来的参数
NSLog(@"%@", call.arguments[@"test"]);
if ([@"goToNativePage" isEqualToString:call.method]) {
//实现跳转的代码
NSString * storyboardName = @"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"NativeViewController"];
vc.navigationItem.title = call.arguments[@"test"];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:vc];
self.navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[controller presentViewController:self.navigationController animated:true completion:nil];
} else {
result(FlutterMethodNotImplemented);
}
}];
在AppDelegate.h 增加一行代码,如下图
@property (nonatomic, strong) UINavigationController *navigationController;
然后就是在Main.storyboard,新增两个控制器分别为NativeViewController和NativeViewControllerTwo,在文件目录里也相应新增两个控制器的.h .m文件
如下图
2个控制器里面的代码也是很简单的
这样就可以愉快地进行测试了.就会达到开篇效果图的样子,达到了混编的目的.
结尾
iOS工程里面的代码是非常简单,就是为了测试用的,测试一下,能不能正常push到下一级界面,能不能pop到上一级界面,能不能直接回到flutter层界面.如果对iOS不熟悉的小伙伴们,可以去探索一下哟.之所以这样操作的意义在于混编,有些在flutter层很难实现的功能,譬如 音视频,图像处理等 ,可以用原生处理好,再回到flutter层,不至于fluter工程,遇到有些功能就卡壳了.
当然了有些功能是可以插件来解决的,通过插件可以达到flutter与原生之间的通信与交互.之前我的文章里也多次提到了,有兴趣的小伙伴们可以去看看我的关于插件的文章.flutter udp multicast 组播插件,flutter 插件的坑都在这里
今天的分享就到这里喽,感觉有点帮助的小伙伴们,帮忙点个赞喽~~
补充
运用上面的思想,是可以行得通的, 我在自己flutter工程里面,把原生工程的视频模块集成到flutter工程啦~~
如下图
前面白色背景的,是flutter工程, 后面黑色背景的视频模块是原生iOS工程,视频模块的功能原封不动的迁移到flutter工程了.