Flutter:基于video_player实现视频相关手势控制、全屏播放
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class VideoPlayerScreen extends StatefulWidget {
final VideoPlayerController controller;
VideoPlayerScreen(this.controller);
@override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
bool _isFullScreen = false;
VideoPlayerController get _controller => widget.controller;
@override
void initState() {
super.initState();
_controller.initialize().then((_) => setState(() {}));
_controller.setLooping(true);
_controller.setVolume(1.0);
_controller.play();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
// 全屏切换逻辑
void _toggleFullScreen() {
setState(() {
_isFullScreen = !_isFullScreen;
});
}
// 全屏视图
Widget _buildFullScreenVideo() {
return Scaffold(
backgroundColor: Colors.black,
body: Center(
child: VideoPlayer(_controller),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggleFullScreen,
child: Icon(Icons.fullscreen_exit),
),
);
}
// 普通视图
Widget _buildNormalVideo() {
return Scaffold(
appBar: AppBar(
title: Text('视频播放'),
),
body: Center(
child: VideoPlayer(_controller),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggleFullScreen,
child: Icon(Icons.fullscreen),
),
);
}
@override
Widget build(BuildContext context) {
return _isFullScreen ? _buildFullScreenVideo() : _buildNormalVideo();
}
}
这段代码实现了一个视频播放器屏幕,它可以在全屏和非全屏模式之间切换。视频播放器控件是使用VideoPlayer
插件创建的,而全屏切换是通过setState来更新当前是否是全屏状态的变量来控制的。这个例子展示了如何在Flutter中管理状态和构建响应式用户界面。
评论已关闭