video_recommend_list_page.dart 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import 'package:better_player_plus/better_player_plus.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_riverpod/flutter_riverpod.dart';
  4. import 'package:news_app/constant/size_res.dart';
  5. import 'package:news_app/ui/video/video_play_item_widget.dart';
  6. import 'package:news_app/util/log.util.dart';
  7. import 'package:visibility_detector/visibility_detector.dart';
  8. import '../../model/video_new_model.dart';
  9. import '../../provider/video_commend_provider.dart';
  10. /// @author: bo.zeng
  11. /// @email: cnhbwds@gmail.com
  12. /// @date: 2025 2025/4/9 16:00
  13. /// @description:
  14. class VideoRecommendListPage extends ConsumerStatefulWidget {
  15. const VideoRecommendListPage({super.key});
  16. @override
  17. ConsumerState<VideoRecommendListPage> createState() =>
  18. _VideoRecommendListPageState();
  19. }
  20. final recommendListProvider =
  21. NotifierProvider<VideoRecommendProvider, List<VideoNewModel>>(() {
  22. return VideoRecommendProvider();
  23. });
  24. // 全局共享的视频控制器
  25. BetterPlayerController? globalVideoController;
  26. class _VideoRecommendListPageState extends ConsumerState<VideoRecommendListPage>
  27. with AutomaticKeepAliveClientMixin {
  28. late final PageController _pageController;
  29. int _currentPageIndex = 0;
  30. String? _currentVideoUrl;
  31. @override
  32. void initState() {
  33. super.initState();
  34. _pageController = PageController();
  35. // 先获取视频数据
  36. ref.read(recommendListProvider.notifier).fetchRecommendVideos();
  37. }
  38. // 安全地执行控制器操作
  39. void _safeControllerOperation(VoidCallback operation) {
  40. if (!mounted) return;
  41. final controller = globalVideoController;
  42. if (controller == null) return;
  43. try {
  44. operation();
  45. } catch (e) {
  46. // 控制器可能已被释放,重置为 null
  47. globalVideoController = null;
  48. }
  49. }
  50. void _playVideo(String url) {
  51. if (!mounted) return;
  52. // 如果是同一个视频,不需要重新加载
  53. if (_currentVideoUrl == url && globalVideoController != null) {
  54. _safeControllerOperation(() {
  55. globalVideoController!.play();
  56. });
  57. return;
  58. }
  59. _currentVideoUrl = url;
  60. // 创建新控制器
  61. globalVideoController = null; // 释放旧的
  62. globalVideoController = BetterPlayerController(
  63. BetterPlayerConfiguration(
  64. autoPlay: true,
  65. looping: true,
  66. aspectRatio: 16 / 9,
  67. fit: BoxFit.fitWidth,
  68. controlsConfiguration: const BetterPlayerControlsConfiguration(
  69. showControls: false,
  70. ),
  71. ),
  72. );
  73. Future.delayed(const Duration(milliseconds: 50), () {
  74. if (!mounted || globalVideoController == null) return;
  75. try {
  76. final dataSource = BetterPlayerDataSource(
  77. BetterPlayerDataSourceType.network,
  78. url,
  79. videoFormat: BetterPlayerVideoFormat.other,
  80. );
  81. globalVideoController!.setupDataSource(dataSource).then((_) {
  82. if (mounted && globalVideoController != null) {
  83. _safeControllerOperation(() {
  84. globalVideoController!.play();
  85. });
  86. }
  87. }).catchError((error) {
  88. globalVideoController = null;
  89. });
  90. } catch (e) {
  91. globalVideoController = null;
  92. }
  93. });
  94. }
  95. @override
  96. void dispose() {
  97. _pageController.dispose();
  98. // 不在这里 dispose 全局控制器
  99. super.dispose();
  100. }
  101. bool _isVisible = false;
  102. void _onVisibilityChanged(VisibilityInfo info) {
  103. if (!mounted) return;
  104. final visible = info.visibleFraction > 0.5;
  105. if (_isVisible != visible) {
  106. setState(() {
  107. _isVisible = visible;
  108. });
  109. }
  110. if (visible) {
  111. consoleLog("页面可见");
  112. _safeControllerOperation(() {
  113. globalVideoController!.play();
  114. });
  115. } else {
  116. consoleLog("页面不可见");
  117. _safeControllerOperation(() {
  118. globalVideoController!.pause();
  119. });
  120. }
  121. }
  122. void _onPageChanged(int index) {
  123. if (!mounted) return;
  124. setState(() {
  125. _currentPageIndex = index;
  126. });
  127. // 页面切换后,播放新视频
  128. final videos = ref.read(recommendListProvider);
  129. if (videos.isNotEmpty && index >= 0 && index < videos.length) {
  130. final url = videos[index].url;
  131. if (url != null && url.isNotEmpty) {
  132. _playVideo(url);
  133. }
  134. }
  135. }
  136. @override
  137. Widget build(BuildContext context) {
  138. super.build(context);
  139. final videos = ref.watch(recommendListProvider);
  140. // 初始化控制器并播放第一个视频
  141. if (videos.isNotEmpty && globalVideoController == null) {
  142. WidgetsBinding.instance.addPostFrameCallback((_) {
  143. final firstUrl = videos.firstOrNull?.url;
  144. if (firstUrl != null && firstUrl.isNotEmpty && mounted) {
  145. _playVideo(firstUrl);
  146. }
  147. });
  148. }
  149. // 视频列表为空时显示加载状态
  150. if (videos.isEmpty) {
  151. return const Center(
  152. child: CircularProgressIndicator(),
  153. );
  154. }
  155. return VisibilityDetector(
  156. key: const Key("value"),
  157. onVisibilityChanged: _onVisibilityChanged,
  158. child: Padding(
  159. padding: EdgeInsets.symmetric(
  160. horizontal: horizontalPadding,
  161. vertical: horizontalPadding,
  162. ),
  163. child: PageView.builder(
  164. controller: _pageController,
  165. onPageChanged: _onPageChanged,
  166. scrollDirection: Axis.vertical,
  167. itemCount: videos.length,
  168. itemBuilder: (context, index) {
  169. // 添加边界检查
  170. if (index < 0 || index >= videos.length) {
  171. return const SizedBox.shrink();
  172. }
  173. final item = videos[index];
  174. return VideoPlayItemWidget(
  175. key: ValueKey("video_${item.contentId ?? index}"),
  176. item: item,
  177. isActive: _isVisible && _currentPageIndex == index,
  178. index: index,
  179. );
  180. },
  181. ),
  182. ),
  183. );
  184. }
  185. @override
  186. bool get wantKeepAlive => true;
  187. }