Flutter中增加PlatformView

东方盛慧科技大约 4 分钟flutterflutter

Flutter中增加PlatformView

基本原理

  • PlatformView是 flutter 官方提供的一个可以嵌入 Android 和 iOS 平台原生 View 的 widget。
  • 利用viewId查找,底层是flutter 引擎进行绘制和渲染。
  • 主要适用于flutter中不太容易实现的widget(Native中已经很成熟,并且很有优势的View),如WebView、视频播放器、地图等。

Flutter和Native有两条通道

  • 用于创建Native View的通道 xx
  • 用于向View传递方法,或者方法回调的通道 xx

使用方法

主要通过创建插件的方式来使用。

创建插件

flutter create --template=plugin platform_view_test

在Flutter层添加

关于controller
class PlatformDemoViewController {
  MethodChannel _channel;
  PlatformDemoViewController.init(int id) {
    _channel = new MethodChannel('platform_view_test_$id');
  }
  Future<void> reloadView() async {
    return _channel.invokeMethod('reloadView');
  }
}
关于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));
  }
}

在Nativie层添加(iOS为例)

关于插件
@implementation PlatformViewTestPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {  
    DemoTestViewFactory* factory = [[DemoTestViewFactory alloc] initWithMessenger:registrar.messenger];
    [registrar registerViewFactory:factory withId:@"plugins.platform_view_test"];
}
@end
关于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
关于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"]) {
// 直接设置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

其他重要的

要在你的 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

过程分析

分析在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。

viewId的产生和传递

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>对象)都存在数组views_中,这样就可以通过viewId进行查找。
另外,所有的 NSObject<FlutterPlatformViewFactory> 对象会存在factories_中,
取出后调用[factory createWithFrame:CGRectZero viewIdentifier:viewId arguments:params]方法就可以创建对应的view。
这个在上面的代码中也定义过了。还有,touch_interceptors_ 数组存储所有的手势 FlutterTouchInterceptingView 对象,应该是用于手势检测。

其他使用例子

上次编辑于:
贡献者: 雷勋