1.1. 基本原理
- PlatformView是 flutter 官方提供的一个可以嵌入 Android 和 iOS 平台原生 View 的 widget。
- 利用viewId查找,底层是flutter 引擎进行绘制和渲染。
- 主要适用于flutter中不太容易实现的widget(Native中已经很成熟,并且很有优势的View),如WebView、视频播放器、地图等。
1.1.1. Flutter和Native有两条通道
-
用于创建Native View的通道
-
用于向View传递方法,或者方法回调的通道
1.2. 使用方法
主要通过创建插件的方式来使用。
1.2.1. 创建插件
flutter create --template=plugin platform_view_test
1.2.2. 在Flutter层添加
1.2.2.1. 关于controller
class PlatformDemoViewController {
MethodChannel _channel;
PlatformDemoViewController.init(int id) {
_channel = new MethodChannel('platform_view_test_$id');
}
Future reloadView() async {
return _channel.invokeMethod('reloadView');
}
}
1.2.2.2. 关于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 {
@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: {
"x": widget.x,
"y": widget.y,
"width": widget.width,
"height": widget.height,
},
creationParamsCodec: const StandardMessageCodec(),
);
} else {
return UiKitView(
viewType: viewTypeString,
onPlatformViewCreated: onPlatformViewCreated,
creationParams: {
"x": widget.x,
"y": widget.y,
"width": widget.width,
"height": widget.height,
},
creationParamsCodec: const StandardMessageCodec(),
);
}
}
Future onPlatformViewCreated(id) async {
if (widget.onCreated == null) {
return;
}
widget.onCreated(new PlatformDemoViewController.init(id));
}
}
1.2.3. 在Nativie层添加(iOS为例)
1.2.3.1. 关于插件
@implementation PlatformViewTestPlugin
+ (void)registerWithRegistrar:(NSObject*)registrar {
DemoTestViewFactory* factory = [[DemoTestViewFactory alloc] initWithMessenger:registrar.messenger];
[registrar registerViewFactory:factory withId:@"plugins.platform_view_test"];
}
@end
1.2.3.2. 关于DemoTestViewFactory
//.h
#import
@interface DemoTestViewFactory : NSObject
- (instancetype)initWithMessenger:(NSObject*)messenger;
@end
//.m
@interface DemoTestViewFactory ()
@property(nonatomic)NSObject* messenger;
@end
@implementation DemoTestViewFactory
- (instancetype)initWithMessenger:(NSObject*)messenger {
self = [super init];
if (self) {
self.messenger = messenger;
}
return self;
}
- (NSObject*)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
- (nonnull NSObject *)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. 关于DemoTestViewController
//.h
@interface DemoTestViewController : NSObject
- (instancetype)initWithWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
binaryMessenger:(NSObject*)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 *)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"]) {
// 直接设置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中添加
io.flutter.embedded_views_preview
如果不添加,则会报错误:
[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层的调用过程。(以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';
最终,调用到引擎层的SceneBuilder_addPlatformView
函数去进行绘制。传入的viewId应该可以找到Native层对应的View。
1.3.2. viewId的产生和传递
- dart层_UiKitViewState中
Future _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 initUiKitView({
@required int id,
@required String viewType,
@required TextDirection layoutDirection,
dynamic creationParams,
MessageCodec creationParamsCodec,
}) async {
final Map args = {
'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('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* args = [call arguments];
long viewId = [args[@"id"] longValue];
std::string viewType([args[@"viewType"] UTF8String]);
NSObject* factory = factories_[viewType].get();
....
id params = nil;
if ([factory respondsToSelector:@selector(createArgsCodec)]) {
NSObject* codec = [factory createArgsCodec];
if (codec != nil && args[@"params"] != nil) {
FlutterStandardTypedData* paramsData = args[@"params"];
params = [codec decode:paramsData.data];
}
}
NSObject* embedded_view = [factory createWithFrame:CGRectZero
viewIdentifier:viewId
arguments:params];
views_[viewId] = fml::scoped_nsobject>([embedded_view retain]);
FlutterTouchInterceptingView* touch_interceptor =
[[[FlutterTouchInterceptingView alloc] initWithEmbeddedView:embedded_view.view
flutterView:flutter_view_] autorelease];
touch_interceptors_[viewId] =
fml::scoped_nsobject([touch_interceptor retain]);
result(nil);
}
通过上面的代码,很容易看出所有的view(NSObject
对象)都存在数组views_中,这样就可以通过viewId进行查找。另外,所有的 NSObject
对象会存在factories_中,取出后调用[factory createWithFrame:CGRectZero viewIdentifier:viewId arguments:params]
方法就可以创建对应的view。这个在上面的代码中也定义过了。还有,touch_interceptors_
数组存储所有的手势 FlutterTouchInterceptingView
对象,应该是用于手势检测。
1.4. 其他使用例子
- Flutter使用 PlatforView 显示 iOS 原生 View
- 跟我一步一步实现 Flutter 视频播放插件 (一)
- Flutter 中嵌入 Native 组件
- 文中git地址