提到flutter 與 原生工程混編,網(wǎng)上找到的資料大多都是介紹, 原生工程怎么去集成flutter,而對(duì)于flutter工程怎么去集成原生工程的介紹,少之又少,即使有介紹,質(zhì)量也不理想,于是產(chǎn)生了寫(xiě)這篇文章的動(dòng)力. 原生工程怎么去集成flutter, 官方有提供出了方案, 還有閑魚(yú)團(tuán)隊(duì),比較成熟的第三方集成方案,這個(gè)小伙伴們自己去探索一下嘍.
回到正題,我們將要探討的是,flutter工程怎么去集成原生工程,下面將會(huì)以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<MyHomePage> {
static const platform =
const MethodChannel('samples.flutter.dev/goToNativePage');
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: 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 頁(yè)面",
style: new TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w900,
fontFamily: "Georgia",
),
)
],
),
),
),
);
}
}
關(guān)鍵的代碼就是調(diào)用MethodChannel相關(guān)方法,與原生進(jìn)行溝通.
static const platform =
const MethodChannel('samples.flutter.dev/goToNativePage');
Future<void> _goToNativePage() async {
try {
final int result = await platform
.invokeMethod('goToNativePage', {'test': 'from flutter'});
print(result);
} on PlatformException catch (e) {}
}
原生層(也就是iOS工程里面)
在A(yíng)ppDelegate.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傳遞過(guò)來(lái)的參數(shù)
NSLog(@"%@", call.arguments[@"test"]);
if ([@"goToNativePage" isEqualToString:call.method]) {
//實(shí)現(xiàn)跳轉(zhuǎn)的代碼
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);
}
}];
在A(yíng)ppDelegate.h 增加一行代碼,如下圖
@property (nonatomic, strong) UINavigationController *navigationController;
然后就是在Main.storyboard,新增兩個(gè)控制器分別為NativeViewController和NativeViewControllerTwo,在文件目錄里也相應(yīng)新增兩個(gè)控制器的.h .m文件
如下圖
2個(gè)控制器里面的代碼也是很簡(jiǎn)單的
這樣就可以愉快地進(jìn)行測(cè)試了.就會(huì)達(dá)到開(kāi)篇效果圖的樣子,達(dá)到了混編的目的.
結(jié)尾
iOS工程里面的代碼是非常簡(jiǎn)單,就是為了測(cè)試用的,測(cè)試一下,能不能正常push到下一級(jí)界面,能不能pop到上一級(jí)界面,能不能直接回到flutter層界面.如果對(duì)iOS不熟悉的小伙伴們,可以去探索一下喲.之所以這樣操作的意義在于混編,有些在flutter層很難實(shí)現(xiàn)的功能,譬如 音視頻,圖像處理等 ,可以用原生處理好,再回到flutter層,不至于fluter工程,遇到有些功能就卡殼了.
當(dāng)然了有些功能是可以插件來(lái)解決的,通過(guò)插件可以達(dá)到flutter與原生之間的通信與交互.之前我的文章里也多次提到了,有興趣的小伙伴們可以去看看我的關(guān)于插件的文章.flutter udp multicast 組播插件,flutter 插件的坑都在這里
今天的分享就到這里嘍,感覺(jué)有點(diǎn)幫助的小伙伴們,幫忙點(diǎn)個(gè)贊嘍~~
補(bǔ)充
運(yùn)用上面的思想,是可以行得通的, 我在自己flutter工程里面,把原生工程的視頻模塊集成到flutter工程啦~~
如下圖
前面白色背景的,是flutter工程, 后面黑色背景的視頻模塊是原生iOS工程,視頻模塊的功能原封不動(dòng)的遷移到flutter工程了.