快捷搜索: 王者荣耀 脱发

Flutter 视频播放器组件封装

添加插件

pubspec.yaml
chewie: ^1.0.0
video_player: ^2.0.2

封装播放器

video_view.dart
class VideoView extends StatefulWidget {
          
   
  final String url; // 播放地址
  final String cover; // 封面
  final bool autoPlay; // 是否自动播放
  final bool looping; // 是否循环
  final double aspectRatio; // 宽高比
  const VideoView(this.url,
      {
          
   Key key, this.cover, this.autoPlay, this.looping, this.aspectRatio})
      : super(key: key);

  @override
  _VideoViewState createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
          
   
  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;

  // 封面 (FractionallySizedBox:可控制组件在水平/垂直方向上填充满父容器)
  get _placeHolder => FractionallySizedBox(
        widthFactor: 1,
        child: cacheImage(widget.cover),
      );

  // 进度条颜色设置
  get _progressColors => ChewieProgressColors(
        playedColor: primary,
        bufferedColor: primary,
        handleColor: Colors.grey,
        backgroundColor: primary[50],
      );

  @override
  void initState() {
          
   
    super.initState();
    _videoPlayerController = VideoPlayerController.network(widget.url);
    _chewieController = ChewieController(
        //要播放的视频的控制器
        videoPlayerController: _videoPlayerController,
        // 缩放比
        aspectRatio: widget.aspectRatio,
        // 是否自动播放
        autoPlay: widget.autoPlay,
        // 封面
        looping: widget.looping,
        // 进度条颜色
        placeholder: _placeHolder,
        // 进度条颜色
        materialProgressColors: _progressColors,
        // 是否静音
        allowMuting: false,
        // 是否显示播放速度
        allowPlaybackSpeedChanging: false,
        customControls: MaterialControls(
          showLoadingOnInitialize: false,
          showBigPlayIcon: false,
          bottomGradient: blackLinearGradient(),
        ));
  }

  @override
  void dispose() {
          
   
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
          
   
    double screenWidth = MediaQuery.of(context).size.width; // 播放器宽度
    double screenHeight = screenWidth / widget.aspectRatio; // 播放器高度
    return Container(
      width: screenWidth,
      height: screenHeight,
      color: Colors.grey,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }
}

自定义播放器UI

经验分享 程序员 微信小程序 职场和发展