flutter Html 加载video适配

场景:Html控件data中含有video样式的,默认情况下video会出现视图拉伸,需要对video

进行调整。以下代码仅支持data中含有一个视频,多个视频的话,需要对应多个controller。

VideoPlayerController videoPlayerController;
ChewieController chewieController;
bool initialized = false;
  
Widget webViewsWidget() {
    double w = ScreenUtils.screenW(context);
    return Container(
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      child: Html(
        // 渲染的数据
        data: model.content,
        // 自定义样式
        style: {
          'video': Style(
            height: w / 1.5,
          ),
        },
        customRender: {
          "video": (RenderContext context, Widget child) {
            return videoLayout(context);
          },
          "flutter": (RenderContext context, Widget child) {
            return FlutterLogo(
              style: (context.tree.element.attributes['horizontal'] != null)
                  ? FlutterLogoStyle.horizontal
                  : FlutterLogoStyle.markOnly,
              textColor: context.style.color,
              size: context.style.fontSize.size * 5,
            );
          },
        },
        onImageError: (exception, stackTrace) {
          print(exception);
        },
      ),
    );
  }

  Widget videoLayout(RenderContext context) {
    // print(context.tree.element.innerHtml);
    //
    String data = context.tree.element.innerHtml;
    String url;
    if (data.isNotEmpty) {
      List list = data.split('"');
      for (String s in list) {
        if (s.contains('https://') || s.contains('http://')) {
          url = s;
        }
      }
    }
    if (url.isEmpty) {
      return SizedBox();
    }
    if (!initialized) {
      videoPlayerController = VideoPlayerController.network(url);
      videoPlayerController.initialize().then((value) {
        print(videoPlayerController.value.size);
        initialized = true;
        chewieController = ChewieController(
          allowFullScreen: true,
          //是否允许全屏
          videoPlayerController: videoPlayerController,
          aspectRatio: videoPlayerController.value.size.width /
              videoPlayerController.value.size.height,
          //宽高比
          autoPlay: false,
          //自动播放
          looping: false, //循环播放
        );
        setState(() {});
      });
    }
    return initialized
        ? Center(
      child: Chewie(
        controller: chewieController,
      ),
    )
        : Container(
      color: Colors.grey,
    );
  }

你可能感兴趣的:(Flutter,flutter)