提到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<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 頁面",
style: new TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w900,
fontFamily: "Georgia",
),
)
],
),
),
),
);
}
}
關鍵的代碼就是調用MethodChannel相關方法,與原生進行溝通.
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工程里面)
在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工程了.