Files
doyin/lib/app/modules/selfMedia/video/views/videoFeed.dart
2025-07-07 18:45:44 +08:00

653 lines
21 KiB
Dart

// import 'package:caller/app/models/videomodels/videosModel.dart';
// import 'package:flutter/material.dart';
// import 'dart:convert';
// import 'package:flutter/services.dart';
// import 'package:chewie/chewie.dart';
// import 'package:video_player/video_player.dart';
//
// import '../widgets/videoWidget.dart';
// class VideoFeedScreen extends StatefulWidget {
// const VideoFeedScreen({super.key});
//
// @override
// _VideoFeedScreenState createState() => _VideoFeedScreenState();
// }
//
// class _VideoFeedScreenState extends State<VideoFeedScreen> {
// final PageController _pageController = PageController();
// List<VideoItemModel> videos = [];
// bool isLoading = true;
//
// @override
// void initState() {
// super.initState();
// _loadVideos();
// }
//
// Future<void> _loadVideos() async {
// try {
// final String response = await rootBundle.loadString('assets/video.json');
// final data = json.decode(response);
// final categories = (data['categories'] as List)
// .map((category) => VideoCategory.fromJson(category))
// .toList();
//
// if (categories.isNotEmpty) {
// setState(() {
// videos = categories.first.videos;
// isLoading = false;
// });
// }
// } catch (e) {
// print('Error loading videos: $e');
// setState(() {
// isLoading = false;
// });
// }
// }
//
// @override
// void dispose() {
// _pageController.dispose();
// super.dispose();
// }
//
// @override
// Widget build(BuildContext context) {
// if (isLoading) {
// return const Center(child: CircularProgressIndicator());
// }
//
// if (videos.isEmpty) {
// return const Center(child: Text('No videos available'));
// }
//
// return Scaffold(
// body: PageView.builder(
// controller: _pageController,
// scrollDirection: Axis.vertical,
// physics: const ClampingScrollPhysics(),
// itemCount: videos.length,
// itemBuilder: (context, index) {
// final video = videos[index];
// late VideoPlayerController videoPlayerController;
//
// return Stack(
// fit: StackFit.expand,
// children: [
// // Video Item (full screen)
// VideoItem(
// videoUrl: video.sources.first,
// index: index,
// onVideoInit: (controller) {
// videoPlayerController = controller;
// },
// ),
// // Overlay UI
// // GestureDetector(
// // onTap: () {
// // if (videoPlayerController.value.isPlaying) {
// // videoPlayerController.pause();
// // } else {
// // videoPlayerController.play();
// // }
// // },
// // child: Container(
// // color: Colors.transparent,
// // ),
// // ),
// // Overlay UI
// _buildVideoOverlay(video, index),
// ],
// );
// },
// ),
// );
// }
//
// Widget _buildVideoOverlay(VideoItemModel video, int index) {
// return Positioned.fill(
// child: Column(
// children: [
// // Top spacer
// Expanded(
// child: Container(),
// ),
//
// // Bottom overlay content
// Container(
// padding: const EdgeInsets.only(bottom: 40, left: 20, right: 20),
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.end,
// children: [
// // Left side - Caption and hashtags
// Expanded(
// child: Column(
// mainAxisSize: MainAxisSize.min,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// '@${video.subtitle.replaceAll('By ', '').replaceAll(' ', '').toLowerCase()}',
// style: const TextStyle(
// color: Colors.white,
// fontWeight: FontWeight.bold,
// fontSize: 16,
// ),
// ),
// const SizedBox(height: 8),
// Text(
// video.description,
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// style: const TextStyle(
// color: Colors.white,
// fontSize: 16,
// ),
// ),
// const SizedBox(height: 8),
// Row(
// children: [
// const Icon(Icons.music_note, color: Colors.white, size: 16),
// const SizedBox(width: 8),
// Text(
// video.title,
// style: const TextStyle(
// color: Colors.white,
// fontSize: 14,
// ),
// ),
// ],
// ),
// ],
// ),
// ),
//
// // Right side - Action buttons
// Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// // User avatar with follow button
// Column(
// children: [
// Stack(
// alignment: Alignment.bottomCenter,
// children: [
// CircleAvatar(
// radius: 25,
// backgroundImage: NetworkImage(video.thumb),
// ),
// Container(
// padding: const EdgeInsets.all(2),
// decoration: const BoxDecoration(
// color: Colors.red,
// shape: BoxShape.circle,
// ),
// child: const Icon(Icons.add, size: 12, color: Colors.white),
// ),
// ],
// ),
// const SizedBox(height: 8),
// ],
// ),
//
// // Like button
// _buildActionButton(Icons.favorite, '${(index + 1) * 1000}'),
// const SizedBox(height: 20),
//
// // Comment button
// _buildActionButton(Icons.comment, '${(index + 1) * 100}'),
// const SizedBox(height: 20),
//
// // Share button
// _buildActionButton(Icons.share, 'Share'),
// const SizedBox(height: 20),
//
// // Music disc
// Container(
// padding: const EdgeInsets.all(8),
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(20),
// border: Border.all(color: Colors.white),
// ),
// child: const Icon(Icons.music_note, color: Colors.white, size: 20),
// ),
// ],
// ),
// ],
// ),
// ),
// ],
// ),
// );
// }
//
// Widget _buildActionButton(IconData icon, String text) {
// return Column(
// children: [
// Icon(icon, color: Colors.white, size: 35),
// const SizedBox(height: 4),
// Text(
// text,
// style: const TextStyle(color: Colors.white, fontSize: 12),
// ),
// ],
// );
// }
// }
// import 'package:flutter/material.dart';
// import 'package:cached_video_player_plus/cached_video_player_plus.dart';
// import '../services/videoPreloader.dart';
// import '../widgets/videoWidget.dart';
// class VideoFeedScreen extends StatefulWidget {
// const VideoFeedScreen({Key? key}) : super(key: key);
// @override
// _VideoFeedScreenState createState() => _VideoFeedScreenState();
// }
// class _VideoFeedScreenState extends State<VideoFeedScreen> {
// final PageController _pageController = PageController();
// final VideoPreloader _preloader = VideoPreloader();
// // Your video URLs from server
// final List<String> videoUrls = [
// 'rtmp://webrtc.test.7games.store/live/test333',
// 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
// 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
// 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4',
// 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4',
// 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4',
// ];
// int currentIndex = 0;
// final Map<int, CachedVideoPlayerPlusController> _controllers = {};
// @override
// void initState() {
// super.initState();
// _initializePreloader();
// }
// void _initializePreloader() async {
// // Configure preloader settings
// _preloader.maxPreloadCount = 2; // Preload 2 videos ahead
// _preloader.maxCacheSize = 200 * 1024 * 1024; // 200MB cache limit
// // Load existing cache entries
// await _preloader.loadExistingCache();
// // Start preloading for current position
// _preloader.preloadVideos(videoUrls, currentIndex);
// }
// void _onVideoInit(int index, CachedVideoPlayerPlusController controller) {
// _controllers[index] = controller;
// }
// void _onVideoDispose(int index) {
// if (_controllers.containsKey(index)) {
// _controllers.remove(index);
// }
// }
// void _onPageChanged(int index) {
// setState(() {
// currentIndex = index;
// });
// // Pause all other videos
// _controllers.forEach((key, controller) {
// if (key == index && _controllers.containsKey(key)) {
// if (!controller.value.isPlaying) {
// controller.play();
// }
// } else {
// if (controller.value.isPlaying) {
// controller.pause();
// }
// }
// });
// // Trigger preloading for new position
// _preloader.preloadVideos(videoUrls, index);
// }
// @override
// void dispose() {
// _controllers.forEach((key, controller) {
// controller.dispose();
// });
// _pageController.dispose();
// super.dispose();
// }
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// backgroundColor: Colors.black,
// appBar: AppBar(
// backgroundColor: Colors.black,
// title: const Text('Video Feed'),
// actions: [
// // Cache info button
// IconButton(
// icon: const Icon(Icons.info),
// onPressed: _showCacheInfo,
// ),
// // Clear cache button
// IconButton(
// icon: const Icon(Icons.clear),
// onPressed: _clearCache,
// ),
// ],
// ),
// body: PageView.builder(
// controller: _pageController,
// scrollDirection: Axis.vertical,
// onPageChanged: _onPageChanged,
// itemCount: videoUrls.length,
// itemBuilder: (context, index) {
// return VideoItem(
// videoUrl: videoUrls[index],
// index: index,
// allVideoUrls: videoUrls,
// onVideoInit: (controller) => _onVideoInit(index, controller),
// onVideoDispose: _onVideoDispose,
// );
// },
// ),
// floatingActionButton: Column(
// mainAxisAlignment: MainAxisAlignment.end,
// children: [
// // Video counter
// Container(
// padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
// decoration: BoxDecoration(
// color: Colors.black54,
// borderRadius: BorderRadius.circular(20),
// ),
// child: Text(
// '${currentIndex + 1}/${videoUrls.length}',
// style: const TextStyle(color: Colors.white),
// ),
// ),
// const SizedBox(height: 16),
// ],
// ),
// );
// }
// void _showCacheInfo() async {
// final cacheSize = await _preloader.getFormattedCacheSize();
// final cachedCount = _preloader.cachedVideoPaths.length;
// showDialog(
// context: context,
// builder: (context) => AlertDialog(
// title: const Text('Cache Information'),
// content: Column(
// mainAxisSize: MainAxisSize.min,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text('Cache Size: $cacheSize'),
// Text('Cached Videos: $cachedCount'),
// Text('Max Cache Size: ${(_preloader.maxCacheSize / (1024 * 1024)).toStringAsFixed(0)}MB'),
// Text('Preload Count: ${_preloader.maxPreloadCount}'),
// ],
// ),
// actions: [
// TextButton(
// onPressed: () => Navigator.pop(context),
// child: const Text('OK'),
// ),
// ],
// ),
// );
// }
// void _clearCache() async {
// showDialog(
// context: context,
// builder: (context) => AlertDialog(
// title: const Text('Clear Cache'),
// content: const Text('Are you sure you want to clear all cached videos?'),
// actions: [
// TextButton(
// onPressed: () => Navigator.pop(context),
// child: const Text('Cancel'),
// ),
// TextButton(
// onPressed: () async {
// Navigator.pop(context);
// await _preloader.clearCache();
// ScaffoldMessenger.of(context).showSnackBar(
// const SnackBar(content: Text('Cache cleared successfully')),
// );
// },
// child: const Text('Clear'),
// ),
// ],
// ),
// );
// }
// }
import 'package:caller/app/modules/chat/MessageModule/views/messageChatViews/ChatHomePage.dart';
import 'package:flutter/material.dart';
import 'package:cached_video_player_plus/cached_video_player_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/videoPreloader.dart';
import '../widgets/videoWidget.dart';
class VideoFeedScreen extends StatefulWidget {
const VideoFeedScreen({Key? key}) : super(key: key);
@override
_VideoFeedScreenState createState() => _VideoFeedScreenState();
}
class _VideoFeedScreenState extends State<VideoFeedScreen> {
final PageController _pageController = PageController();
final VideoPreloader _preloader = VideoPreloader();
final List<String> videoUrls = [
'rtmp://webrtc.test.7games.store/live/test333',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4',
];
int currentIndex = 0;
final Map<int, CachedVideoPlayerPlusController> _controllers = {};
@override
void initState() {
super.initState();
_initializePreloader();
_loadSavedIndex();
}
void _initializePreloader() async {
_preloader.maxPreloadCount = 3;
_preloader.maxCacheSize = 200 * 1024 * 1024;
await _preloader.loadExistingCache();
_preloader.preloadVideos(videoUrls, currentIndex);
}
void _loadSavedIndex() async {
final prefs = await SharedPreferences.getInstance();
final savedIndex = prefs.getInt('lastVideoIndex') ?? 0;
setState(() {
currentIndex = savedIndex.clamp(0, videoUrls.length - 1);
});
// jump to saved index
_pageController.jumpToPage(currentIndex);
// also start preloading for this index
_preloader.preloadVideos(videoUrls, currentIndex);
}
void _onVideoInit(int index, CachedVideoPlayerPlusController controller) {
_controllers[index] = controller;
}
void _onVideoDispose(int index) {
if (_controllers.containsKey(index)) {
_controllers.remove(index);
}
}
void _onPageChanged(int index) async {
setState(() {
currentIndex = index;
});
// Save current index locally
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('lastVideoIndex', currentIndex);
// Pause others
_controllers.forEach((key, controller) {
if (key == index && _controllers.containsKey(key)) {
if (!controller.value.isPlaying) {
controller.play();
}
} else {
if (controller.value.isPlaying) {
controller.pause();
}
}
});
// Preload next videos
_preloader.preloadVideos(videoUrls, index);
}
@override
void dispose() {
_controllers.forEach((key, controller) {
controller.dispose();
});
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
title: const Text('Video Feed'),
actions: [
IconButton(
icon: const Icon(Icons.switch_account),
onPressed: ()=>Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=>ChatHomeScreen())),
),
// IconButton(
// icon: const Icon(Icons.info),
// onPressed: _showCacheInfo,
// ),
// IconButton(
// icon: const Icon(Icons.clear),
// onPressed: _clearCache,
// ),
],
),
body: PageView.builder(
controller: _pageController,
scrollDirection: Axis.vertical,
onPageChanged: _onPageChanged,
itemCount: videoUrls.length,
itemBuilder: (context, index) {
return VideoItem(
videoUrl: videoUrls[index],
index: index,
allVideoUrls: videoUrls,
// onVideoInit: (controller) => _onVideoInit(index, controller),
// onVideoDispose: _onVideoDispose,
);
},
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(20),
),
child: Text(
'${currentIndex + 1}/${videoUrls.length}',
style: const TextStyle(color: Colors.white),
),
),
const SizedBox(height: 16),
],
),
);
}
void _showCacheInfo() async {
final cacheSize = await _preloader.getFormattedCacheSize();
final cachedCount = _preloader.cachedVideoPaths.length;
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Cache Information'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Cache Size: $cacheSize'),
Text('Cached Videos: $cachedCount'),
Text('Max Cache Size: ${(_preloader.maxCacheSize / (1024 * 1024)).toStringAsFixed(0)}MB'),
Text('Preload Count: ${_preloader.maxPreloadCount}'),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
}
void _clearCache() async {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Clear Cache'),
content: const Text('Are you sure you want to clear all cached videos?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
Navigator.pop(context);
await _preloader.clearCache();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Cache cleared successfully')),
);
},
child: const Text('Clear'),
),
],
),
);
}
}