『Flutter』封装原生组件给flutter使用

Flutter嵌套原生View。
还是最近的工作内容,把原生直播播放器嵌套到flutter内,引出的东西。

本篇通过这个需求,引出牵扯的东西吧。
如果要把原生组件嵌套到flutter中,那么我们需要认识一下下面几个东西。
FlutterPlugin
注册FlutterPlatformViewFactory对象的方法

/**
 * Registers a `FlutterPlatformViewFactory` for creation of platform views.
 *
 * Plugins can expose a `UIView` for embedding in Flutter apps by registering a view factory.
 *
 * @param factory The view factory that will be registered.
 * @param factoryId A unique identifier for the factory, the Dart code of the Flutter app can use
 *   this identifier to request creation of a `UIView` by the registered factory.
 * @param gestureRecognizersBlockingPolicy How UIGestureRecognizers on the platform views are
 * blocked.
 *
 */
- (void)registerViewFactory:(NSObject<FlutterPlatformViewFactory>*)factory
                     withId:(NSString*)factoryId;

FlutterPlatformViewFactory负责嵌套原生的工厂类。

FLUTTER_DARWIN_EXPORT
@protocol FlutterPlatformViewFactory <NSObject>
/**
 * Create a `FlutterPlatformView`.
 *
 * Implemented by iOS code that expose a `UIView` for embedding in a Flutter app.
 *
 * The implementation of this method should create a new `UIView` and return it.
 *
 * @param frame The rectangle for the newly created `UIView` measured in points.
 * @param viewId A unique identifier for this `UIView`.
 * @param args Parameters for creating the `UIView` sent from the Dart side of the Flutter app.
 *   If `createArgsCodec` is not implemented, or if no creation arguments were sent from the �Dart
 *   code, this will be null. Otherwise this will be the value sent from the Dart code as decoded by
 *   `createArgsCodec`.
 */
- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
                                   viewIdentifier:(int64_t)viewId
                                        arguments:(id _Nullable)args;

/**
 * Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`.
 *
 * Only needs to be implemented if `createWithFrame` needs an arguments parameter.
 */
@optional
- (NSObject<FlutterMessageCodec>*)createArgsCodec;
@end

FlutterPlatformView 包裹原生组件的flutterView

@protocol FlutterPlatformView <NSObject>
/**
 * Returns a reference to the `UIView` that is wrapped by this `FlutterPlatformView`.
 */
- (UIView*)view;
@end

答题的思路在于,通过FlutterPlatformViewFactory协议,来创建工厂对象,并通过工厂类的create方法,创建嵌套原生的flutterView。


// 直播播放器
public class ZLFlutterRTCLivePlayViewFactory : NSObject,FlutterPlatformViewFactory{
    
    public static let SIGN = "ZLFlutterRTCLivePlayView";
    private var message : FlutterBinaryMessenger;
    
    init(message : FlutterBinaryMessenger) {
        self.message = message;
    }
    
    public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
        // 绑定方法监听
        let channel = FlutterMethodChannel(
            name: "\(ZLFlutterRTCLivePlayViewFactory.SIGN)_\(viewId)",
            binaryMessenger: message
        )
        let view = ZLFlutterRTCLivePlayView(frame, channel: channel);
        channel.setMethodCallHandler(view.handle);
        return view;
    }
}

class ZLFlutterRTCLivePlayView : NSObject,FlutterPlatformView{
    private lazy var playView : UIView = {
        return UIView();
    }(); // 播放View
    private var frame: CGRect?;
    private var channel: FlutterMethodChannel?
    
    private lazy var player: TXLivePlayer = { // 播放器
        let livePlayer = TXLivePlayer()
        livePlayer.delegate = self
        return livePlayer
    }()
    
    init(_ frame : CGRect, channel: FlutterMethodChannel?) {
        super.init()
        self.frame = frame;
        self.channel = channel;
    }
    
    public func view() -> UIView {
        return playView;
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "startPlay":
            startPlay(call, result: result);
            break;
        case "stopPlay":
            stopPlay(call, result: result);
            break;
        case "setMute":
            setMute(call, result: result);
            break;
        case "setRenderMode":
            setRenderMode(call, result: result);
            break;
        case "setRenderRotation":
            setRenderRotation(call, result: result);
            break;
        default:
            result(FlutterMethodNotImplemented);
        }
    }
    
    private func startPlay(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if let url = CommonUtils.getParamByKey(call: call, result: result, param: "url") as? String,
           let type = CommonUtils.getParamByKey(call: call, result: result, param: "type") as? Int,
           let playType = TX_Enum_PlayType(rawValue: type) {
            player.setupVideoWidget(frame ?? CGRect.zero, contain: self.playView, insert: 0)
            player.startPlay(url, type: .PLAY_TYPE_VOD_HLS)
        }
        result(nil)
    }
    
    private func stopPlay(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        player.stopPlay()
        player.removeVideoWidget()
        result(nil)
    }
    
    private func setMute(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if let mute = CommonUtils.getParamByKey(call: call, result: result, param: "url") as? Bool {
            player.setMute(mute)
        }
        
        result(nil)
    }
    
    private func setRenderMode(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if let value = CommonUtils.getParamByKey(call: call, result: result, param: "renderMode") as? Int,
           let renderMode = TX_Enum_Type_RenderMode.init(rawValue: value) {
            self.player.setRenderMode(renderMode)
        }
        
        result(nil)
    }
    
    private func setRenderRotation(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if let value = CommonUtils.getParamByKey(call: call, result: result, param: "rotation") as? Int,
           let rotation = TX_Enum_Type_HomeOrientation.init(rawValue: value) {
            self.player.setRenderRotation(rotation)
        }
        
        result(nil)
    }
}

通过FlutterPlugin来注册工厂类。

public static func register(with registrar: FlutterPluginRegistrar) {
        // 直播播放器
        let playViewFactory = ZLFlutterRTCLivePlayViewFactory(message: registrar.messenger());
        registrar.register(
            playViewFactory,
            withId: ZLFlutterRTCLivePlayViewFactory.SIGN
        );
    }

对于flutter端的代码,通过channelType来进行原生flutter的交互。


/// 直播播放器
class ZLPlayView extends StatefulWidget {
  /// @nodoc
  /// channel标识符
  static String channelType = "ZLFlutterRTCLivePlayView";
  final ValueChanged<int>? onViewCreated;
  final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;
  const ZLPlayView({Key? key, this.onViewCreated, this.gestureRecognizers})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => ZLPlayViewState();
}

//// @nodoc
class ZLPlayViewState extends State<ZLPlayView> {
  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) {
      return AndroidView(
        viewType: ZLPlayView.channelType,
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        viewType: ZLPlayView.channelType,
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
      );
    } else {
      return Text("该平台不支持Platform View");
    }
  }

  void _onPlatformViewCreated(int id) {
    if (widget.onViewCreated != null) {
      widget.onViewCreated!(id);
    }
  }
}

typedef ZLPlayOnPlayEvent = void Function(int id, Map param);

/// @nodoc
/// Weex页面控制器方法
class ZLPlayViewController {
  late final MethodChannel _channel;
  ZLPlayOnPlayEvent? _onPlayEvent;

  ZLPlayViewController(int id) {
    _channel = new MethodChannel(ZLPlayView.channelType + '_$id');
    _channel.setMethodCallHandler((methodCall) async {
      switch (methodCall.method) {
        case 'onPlayEvent':
          int id = methodCall.arguments['EvtID'] ?? 0;
          Map param = methodCall.arguments['param'] ?? {};
          if (_onPlayEvent != null) {
            _onPlayEvent!(id, param);
          }
          throw MissingPluginException();
        case 'onNetStatus':
          throw MissingPluginException();
        default:
          throw MissingPluginException();
      }
    });
  }

  setOnPlayEvent(ZLPlayOnPlayEvent onPlayEvent) {
    _onPlayEvent = onPlayEvent;
  }

  /// @description: 开始播放
  /// @param url: 播放地址
  /// @param type: 播放类型
  /// @return void
  Future<void> startPlay(String url, ZLPlayType type) {
    return _channel.invokeMethod('startPlay', {"url": url, "type": type.index});
  }

  /// @description: 停止播放
  /// @return void
  Future<void> stopPlay() {
    return _channel.invokeMethod('stopPlay');
  }

  /// @description: 设置静音
  /// @param mute: true 静音
  /// @return void
  Future<void> setMute(bool mute) {
    return _channel.invokeMethod('setMute', {"mute": mute});
  }

  /// @description: 设置画面的裁剪模式
  /// @param setRenderMode: 模式
  /// @return void
  Future<void> setRenderMode(ZLPlayViewRenderMode renderMode) {
    return _channel
        .invokeMethod('setRenderMode', {"renderMode": renderMode.index});
  }

  /// @description: 设置画面的方向
  /// @param rotation: 方向
  /// @return void
  Future<void> setRenderRotation(ZLPlayViewHomeOrientation rotation) {
    return _channel
        .invokeMethod('setRenderRotation', {"rotation": rotation.index});
  }
}

如果使用的话,最好在外面再套一层业务层来使用。


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

推荐阅读更多精彩内容