Flutter中如何为Chewie视频播放器添加返回按钮
解决方案
不用修改Chewie源码,通过自定义控件组合默认控件的方式就能实现,既保留原有控件的隐藏/显示动画,又能添加返回按钮,具体实现如下:
- 自定义继承自
MaterialControls的控件类,在原有布局基础上添加返回按钮:
class CustomVideoControls extends MaterialControls { @override Widget build(BuildContext context) { return Stack( children: [ // 保留默认控件的全部功能与动画逻辑 super.build(context), // 绑定父类的_showControls状态,实现按钮与默认控件同步显隐 Visibility( visible: _showControls, child: Positioned( left: 16, top: MediaQuery.of(context).padding.top + 16, child: IconButton( icon: const Icon(Icons.arrow_back, color: Colors.white), onPressed: () => Navigator.pop(context), ), ), ), ], ); } }
- 修改你的
ChewieController配置,加入自定义控件参数:
void _initializeVideoPlayer() { final videoPlayerController = widget.galleryItems[0].url != null ? VideoPlayerController.network(widget.galleryItems[0].url!) : VideoPlayerController.file(widget.galleryItems[0].file!); _chewieController = ChewieController( videoPlayerController: videoPlayerController, allowFullScreen: true, autoInitialize: true, looping: false, showControlsOnInitialize: false, hideControlsTimer: const Duration(seconds: 4), autoPlay: true, allowMuting: true, allowPlaybackSpeedChanging: false, materialProgressColors: ChewieProgressColors( playedColor: AppColors.primaryColor, handleColor: AppColors.primaryColor, backgroundColor: Colors.grey, bufferedColor: Colors.grey.withOpacity(0.5), ), errorBuilder: (context, errorMessage) { return Center( child: Text(errorMessage), ); }, // 传入自定义控件 customControls: const CustomVideoControls(), ); }
这样返回按钮会完全同步Chewie默认控件的隐藏/显示动画,无需修改Chewie源码即可实现需求。
内容的提问来源于stack exchange,提问作者ololo
相关产品推荐
相关产品推荐

