You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web中如何设置VideoPlayer宽高以适配父容器

Flutter Web端VideoPlayer适配容器宽度解决方案

我使用VideoPlayer播放在线.mp4视频时,Android端设置宽高后显示符合预期,但Web端视频宽度无法匹配容器宽度。当前代码如下:

Container(      
  alignment: Alignment.center,
  margin: const EdgeInsets.only(top: 20),
  height: 130,
  width: MediaQuery.of(context).size.width,
  decoration: BoxDecoration(
     borderRadius: BorderRadius.circular(8.0),
     color: Colors.black12, 
     border: Border.all(color: Colors.black)
  ),
  child: SizedBox(
    width: double.infinity,
    child: ClipRRect(
      borderRadius: BorderRadius.circular(8), 
      child: VideoPlayer(HomePage._controller1)
    )
  )
),

Web端显示状态为视频未占满容器宽度,以下是几种适配方案:

方案一:用FittedBox强制填充容器

通过FittedBox包裹VideoPlayer,选择合适的适配模式让视频填充父容器,同时保留圆角裁剪:

Container(
  alignment: Alignment.center,
  margin: const EdgeInsets.only(top: 20),
  height: 130,
  width: MediaQuery.of(context).size.width,
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(8.0),
    color: Colors.black12,
    border: Border.all(color: Colors.black),
  ),
  child: ClipRRect(
    borderRadius: BorderRadius.circular(8),
    child: FittedBox(
      fit: BoxFit.cover, // 保持比例裁剪超出部分,可选BoxFit.fill强制拉伸填充
      child: SizedBox(
        width: MediaQuery.of(context).size.width,
        height: 130,
        child: VideoPlayer(HomePage._controller1),
      ),
    ),
  ),
)

方案二:初始化时设置视频播放尺寸

在VideoPlayerController初始化完成后,直接指定视频的播放尺寸匹配容器:

// 初始化控制器时添加尺寸设置
HomePage._controller1 = VideoPlayerController.networkUrl(Uri.parse("你的视频URL"))
  ..initialize().then((_) {
    setState(() {
      HomePage._controller1.setVideoSize(
        MediaQuery.of(context).size.width,
        130,
      );
    });
  });

注意:如果页面尺寸可能变化(比如窗口缩放),需要监听MediaQuery的变化,重新调用setVideoSize更新尺寸。

方案三:针对Web端调整底层渲染样式

Flutter Web的VideoPlayer基于HTML的video标签,可通过修改其样式强制占满容器(需依赖dart:html):

import 'dart:html' as html;

// 控制器初始化后执行
HomePage._controller1.initialize().then((_) {
  final videoElement = html.document.querySelector('video') as html.VideoElement;
  videoElement.style.width = '100%';
  videoElement.style.height = '100%';
  setState(() {});
});

内容的提问来源于stack exchange,提问作者MrSalesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:57:13