flutter中增加PlatformView

1.1. 基本原理

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

1.1.1. Flutter和Native有两条通道

  • 用于创建Native View的通道


    20190420_flutter_platform_view.png
  • 用于向View传递方法,或者方法回调的通道


    20190420_flutter_platform_view-1.png

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<void> 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<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. 关于插件

@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. 关于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. 关于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

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层的调用过程。(以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<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 对象,应该是用于手势检测。

1.4. 其他使用例子

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容

  • 周瑜很嫉妒诸葛亮的才能。 有一天周瑜找诸葛亮商议军事说到要和曹军交水战,需要 十万只箭。周瑜想要诸葛亮...
    老色批阅读 333评论 0 0
  • 花开在幽谷 你 开在了我的梦里 一笑 成了最初的月 这光辉纯净而清澈 漫过星光漫过高山 漫过钢筋水泥的丛林 漫过李...
    凡夫555阅读 461评论 3 11
  • 今天是会计学院秋游的日子。早晨七点钟太阳还没有露面,天空灰蒙蒙的,似乎预示着今天将会是阴气沉沉的天气。但是车队出发...
    长江秋水阅读 315评论 0 0