1.1. 基本原理
- PlatformView是 flutter 官方提供的一個可以嵌入 Android 和 iOS 平臺原生 View 的 widget。
- 利用viewId查找,底層是flutter 引擎進行繪制和渲染。
- 主要適用于flutter中不太容易實現(xiàn)的widget(Native中已經(jīng)很成熟,并且很有優(yōu)勢的View),如WebView、視頻播放器、地圖等。
1.1.1. Flutter和Native有兩條通道
-
用于創(chuàng)建Native View的通道
20190420_flutter_platform_view.png -
用于向View傳遞方法,或者方法回調(diào)的通道
20190420_flutter_platform_view-1.png
1.2. 使用方法
主要通過創(chuàng)建插件的方式來使用。
1.2.1. 創(chuàng)建插件
flutter create --template=plugin platform_view_test
1.2.2. 在Flutter層添加
1.2.2.1. 關(guān)于controller
class PlatformDemoViewController {
MethodChannel _channel;
PlatformDemoViewController.init(int id) {
_channel = new MethodChannel('platform_view_test_$id');
}
Future<void> reloadView() async {
return _channel.invokeMethod('reloadView');
}
}
1.2.2.2. 關(guān)于PlatformDemoView
const String viewTypeString = 'plugins.platform_view_test';
typedef void PlatformDemoViewCreatedCallback(PlatformDemoViewController controller);
class PlatformDemoView extends StatefulWidget {
final PlatformDemoViewCreatedCallback onCreated;
final x;
final y;
final width;
final height;
PlatformDemoView({
Key key,
@required this.onCreated,
@required this.x,
@required this.y,
@required this.width,
@required this.height,
});
@override
_PlatformDemoViewState createState() => _PlatformDemoViewState();
}
class _PlatformDemoViewState extends State<PlatformDemoView> {
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
child: _nativeView(),
onTapDown: (TapDownDetails details) {
print("onTapDown: ${details.globalPosition}");
},
);
}
Widget _nativeView() {
if (Platform.isAndroid) {
return AndroidView(
viewType: viewTypeString,
onPlatformViewCreated: onPlatformViewCreated,
creationParams: <String, dynamic>{
"x": widget.x,
"y": widget.y,
"width": widget.width,
"height": widget.height,
},
creationParamsCodec: const StandardMessageCodec(),
);
} else {
return UiKitView(
viewType: viewTypeString,
onPlatformViewCreated: onPlatformViewCreated,
creationParams: <String, dynamic>{
"x": widget.x,
"y": widget.y,
"width": widget.width,
"height": widget.height,
},
creationParamsCodec: const StandardMessageCodec(),
);
}
}
Future<void> onPlatformViewCreated(id) async {
if (widget.onCreated == null) {
return;
}
widget.onCreated(new PlatformDemoViewController.init(id));
}
}
1.2.3. 在Nativie層添加(iOS為例)
1.2.3.1. 關(guān)于插件
@implementation PlatformViewTestPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
DemoTestViewFactory* factory = [[DemoTestViewFactory alloc] initWithMessenger:registrar.messenger];
[registrar registerViewFactory:factory withId:@"plugins.platform_view_test"];
}
@end
1.2.3.2. 關(guān)于DemoTestViewFactory
//.h
#import <Flutter/Flutter.h>
@interface DemoTestViewFactory : NSObject<FlutterPlatformViewFactory>
- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
@end
//.m
@interface DemoTestViewFactory ()
@property(nonatomic)NSObject<FlutterBinaryMessenger>* messenger;
@end
@implementation DemoTestViewFactory
- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
self = [super init];
if (self) {
self.messenger = messenger;
}
return self;
}
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
- (nonnull NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
DemoTestViewController *controller = [[DemoTestViewController alloc] initWithWithFrame:frame viewIdentifier:viewId arguments:args binaryMessenger:_messenger];
return controller;
}
@end
1.2.3.3. 關(guān)于DemoTestViewController
//.h
@interface DemoTestViewController : NSObject<FlutterPlatformView>
- (instancetype)initWithWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
@end
//.m
@interface DemoTestViewController ()
@property(nonatomic)UIView * testView;
@property(nonatomic)int64_t viewId;
@property(nonatomic)FlutterMethodChannel* channel;
@property(nonatomic, assign)CGRect viewRect;
@end
@implementation DemoTestViewController
- (instancetype)initWithWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id)args binaryMessenger:(NSObject<FlutterBinaryMessenger> *)messenger{
if ([super init]) {
NSDictionary *dic = args;
NSLog(@"dic = %@", dic);
double x = [dic[@"x"] doubleValue];
double y = [dic[@"y"] doubleValue];
double width = [dic[@"width"] doubleValue];
double height = [dic[@"height"] doubleValue];
self.viewRect = CGRectMake(x, y, width, height);
self.testView = [[UIView alloc] initWithFrame:CGRectZero];
self.testView.backgroundColor = [UIColor redColor];
self.viewId = viewId;
NSString* channelName = [NSString stringWithFormat:@"platform_view_test_%lld", viewId];
self.channel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:messenger];
__weak __typeof__(self) weakSelf = self;
[self.channel setMethodCallHandler:^(FlutterMethodCall * call, FlutterResult result) {
[weakSelf onMethodCall:call result:result];
}];
}
return self;
}
-(UIView *)view{
return self.testView;
}
-(void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result{
if ([[call method] isEqualToString:@"loadUrl"]) {
__weak __typeof__(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
weakSelf.testView.backgroundColor = [UIColor blueColor];
});
} else if ([[call method] isEqualToString:@"reloadView"]) {
// 直接設(shè)置frame不起作用,但是延遲一個時間后就會起作用。
// self.testView.frame = self.viewRect;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.testView.frame = self.viewRect;
});
} else {
result(FlutterMethodNotImplemented);
}
}
@end
1.2.4. 其他重要的
要在你的 info.plist中添加
<key>io.flutter.embedded_views_preview</key><true/>
如果不添加,則會報錯誤:
[VERBOSE-2:platform_view_layer.cc(19)] Trying to embed a platform view but the PrerollContext does not support embedding
1.3. 過程分析
1.3.1. 分析在flutter層的調(diào)用過程。(以UIKitView為例)
UIKitView
-->_UiKitViewState
-->_UiKitPlatformView
-->RenderUiKitView
-->PlatformViewLayer
-->ui.SceneBuilder.addPlatformView
-->_addPlatformView()
void _addPlatformView(double dx, double dy, double width, double height, int viewId) native 'SceneBuilder_addPlatformView';
最終,調(diào)用到引擎層的SceneBuilder_addPlatformView函數(shù)去進行繪制。傳入的viewId應(yīng)該可以找到Native層對應(yīng)的View。
1.3.2. viewId的產(chǎn)生和傳遞
- dart層_UiKitViewState中
Future<void> _createNewUiKitView() async {
final int id = platformViewsRegistry.getNextPlatformViewId();
final UiKitViewController controller = await PlatformViewsService.initUiKitView(
id: id,
viewType: widget.viewType,
layoutDirection: _layoutDirection,
creationParams: widget.creationParams,
creationParamsCodec: widget.creationParamsCodec,
);
.....
}
-
PlatformViewsService類中
static Future<UiKitViewController> initUiKitView({
@required int id,
@required String viewType,
@required TextDirection layoutDirection,
dynamic creationParams,
MessageCodec<dynamic> creationParamsCodec,
}) async {
final Map<String, dynamic> args = <String, dynamic>{
'id': id,
'viewType': viewType,
};
if (creationParams != null) {
final ByteData paramsByteData = creationParamsCodec.encodeMessage(creationParams);
args['params'] = Uint8List.view(
paramsByteData.buffer,
0,
paramsByteData.lengthInBytes,
);
}
await SystemChannels.platform_views.invokeMethod<void>('create', args);
return UiKitViewController._(id, layoutDirection);
}
這里傳遞到Native層中platform_views里面的create方法。通過字符串 flutter/platform_views 識別。Native層在shell/platform/darwin/ios/framework/Source/FlutterEngine.mm 文件中進行登記。
- 在FlutterPlatformViews中處理
位置在shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm。
void FlutterPlatformViewsController::OnCreate(FlutterMethodCall* call, FlutterResult& result) {
....
NSDictionary<NSString*, id>* args = [call arguments];
long viewId = [args[@"id"] longValue];
std::string viewType([args[@"viewType"] UTF8String]);
NSObject<FlutterPlatformViewFactory>* factory = factories_[viewType].get();
....
id params = nil;
if ([factory respondsToSelector:@selector(createArgsCodec)]) {
NSObject<FlutterMessageCodec>* codec = [factory createArgsCodec];
if (codec != nil && args[@"params"] != nil) {
FlutterStandardTypedData* paramsData = args[@"params"];
params = [codec decode:paramsData.data];
}
}
NSObject<FlutterPlatformView>* embedded_view = [factory createWithFrame:CGRectZero
viewIdentifier:viewId
arguments:params];
views_[viewId] = fml::scoped_nsobject<NSObject<FlutterPlatformView>>([embedded_view retain]);
FlutterTouchInterceptingView* touch_interceptor =
[[[FlutterTouchInterceptingView alloc] initWithEmbeddedView:embedded_view.view
flutterView:flutter_view_] autorelease];
touch_interceptors_[viewId] =
fml::scoped_nsobject<FlutterTouchInterceptingView>([touch_interceptor retain]);
result(nil);
}
通過上面的代碼,很容易看出所有的view(NSObject<FlutterPlatformView>對象)都存在數(shù)組views_中,這樣就可以通過viewId進行查找。另外,所有的 NSObject<FlutterPlatformViewFactory> 對象會存在factories_中,取出后調(diào)用[factory createWithFrame:CGRectZero viewIdentifier:viewId arguments:params]方法就可以創(chuàng)建對應(yīng)的view。這個在上面的代碼中也定義過了。還有,touch_interceptors_ 數(shù)組存儲所有的手勢 FlutterTouchInterceptingView 對象,應(yīng)該是用于手勢檢測。

