团队作业博客(十一)实现查看视频

import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';

void main() {
runApp(MaterialApp(
home: Video1(),
));
}

class Video1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: VideoListPage(),
);
}
}

class VideoListPage extends StatelessWidget {
final List<String> videoThumbnails = [
'assets/images/video_thumbnail0.jpg',
'assets/images/video_thumbnail1.jpg',
'assets/images/video_thumbnail2.jpg',

];

final List<String> videoFiles = [
'assets/video/video0.mp4',
'assets/video/video1.mp4',
'assets/video/video2.mp4',
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('视频列表'),
),
body: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: videoThumbnails.length,
itemBuilder: (context, index) {
return _buildVideoListItem(context, index);
},
),
);
}

Widget _buildVideoListItem(BuildContext context, int index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerPage(videoFile: videoFiles[index]),
),
);
},
child: Column(
children: <Widget>[
AspectRatio(

aspectRatio: 4 / 3, // 保持视频缩略图宽高比为16:9
child: Container(
width: MediaQuery.of(context).size.width / 2 - 16, // 容器宽度,适应网格列宽
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(videoThumbnails[index]),
fit: BoxFit.cover, // 强制缩放以适应容器大小
),
),
),
),
SizedBox(height: 0), // 减少上下间隔
Text('视频 $index', textAlign: TextAlign.center),
],
),
);
}
}

class VideoPlayerPage extends StatefulWidget {
final String videoFile;

VideoPlayerPage({required this.videoFile});

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

class _VideoPlayerPageState extends State<VideoPlayerPage> {
late VideoPlayerController videoPlayerController;

@override
void initState() {
super.initState();
videoPlayerController = VideoPlayerController.asset(widget.videoFile)
..initialize().then((_) {
if (mounted) {
setState(() {});
}
});
}

@override
void dispose() {
videoPlayerController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('视频播放'),
),
body: Center(
child: AspectRatio(
aspectRatio: videoPlayerController.value.aspectRatio,
child: Chewie(
controller: ChewieController(
videoPlayerController: videoPlayerController,
autoPlay: false,
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (videoPlayerController.value.isPlaying) {
videoPlayerController.pause();
} else {
videoPlayerController.play();
}
});
},
child: Icon(
videoPlayerController.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}

 

posted @ 2024-06-14 15:46  财神给你送元宝  阅读(16)  评论(0编辑  收藏  举报