Atualição da appbar | coreção de inserção de dados | outras optimizaçoes
This commit is contained in:
@@ -3,6 +3,7 @@ import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:lottie/lottie.dart';
|
||||
|
||||
import '../widgets/app_gradients.dart';
|
||||
import '../widgets/entrance.dart';
|
||||
import '../widgets/tap_bounce.dart';
|
||||
|
||||
@@ -20,6 +21,9 @@ class CuriosidadeScreen extends StatelessWidget {
|
||||
backgroundColor: _teal,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: kAppBarGradient),
|
||||
),
|
||||
title: const Text(
|
||||
'Curiosidades',
|
||||
style: TextStyle(fontWeight: FontWeight.w900),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../widgets/app_gradients.dart';
|
||||
|
||||
class TermsScreen extends StatelessWidget {
|
||||
const TermsScreen({super.key});
|
||||
|
||||
@@ -13,6 +15,9 @@ class TermsScreen extends StatelessWidget {
|
||||
backgroundColor: _teal,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: kAppBarGradient),
|
||||
),
|
||||
title: const Text(
|
||||
'Termos de Serviço',
|
||||
style: TextStyle(fontWeight: FontWeight.w900),
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:lottie/lottie.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
|
||||
|
||||
import '../widgets/app_gradients.dart';
|
||||
import '../widgets/entrance.dart';
|
||||
import '../widgets/tap_bounce.dart';
|
||||
|
||||
@@ -110,8 +111,48 @@ final List<VideoData> videoList = [
|
||||
),
|
||||
];
|
||||
|
||||
// Cache for video controllers to avoid re-initializing
|
||||
// Cache de controllers de vídeo, partilhado entre qualquer ecrã que mostre
|
||||
// uma prévia (grelha de vídeos e o cartão em destaque na Home). Como vários
|
||||
// widgets podem apontar para o mesmo controller ao mesmo tempo, mantemos uma
|
||||
// contagem de referências para só o libertar quando ninguém mais o usa.
|
||||
final Map<String, VideoPlayerController> _videoControllerCache = {};
|
||||
final Map<String, int> _videoControllerRefCounts = {};
|
||||
|
||||
// Dispositivos (sobretudo emuladores) só suportam um número pequeno de
|
||||
// decodificadores de vídeo/áudio simultâneos. A grelha de vídeos pode ter
|
||||
// dezenas de prévias e o GridView constrói várias de uma vez ao rolar; sem
|
||||
// este limite, cada thumbnail tenta abrir o seu próprio decoder e o sistema
|
||||
// trava (era exatamente isto que causava o congelamento e perda de som ao
|
||||
// navegar por muitos vídeos). Acima do limite, a prévia simplesmente mostra
|
||||
// o ícone de play em vez do frame real do vídeo.
|
||||
const int _maxConcurrentThumbnailDecoders = 1;
|
||||
|
||||
bool get _hasThumbnailDecoderSlot =>
|
||||
_videoControllerCache.length < _maxConcurrentThumbnailDecoders;
|
||||
|
||||
void _releaseVideoController(String path) {
|
||||
final remaining = (_videoControllerRefCounts[path] ?? 0) - 1;
|
||||
if (remaining > 0) {
|
||||
_videoControllerRefCounts[path] = remaining;
|
||||
return;
|
||||
}
|
||||
_videoControllerRefCounts.remove(path);
|
||||
_videoControllerCache.remove(path)?.dispose();
|
||||
}
|
||||
|
||||
/// Descarta TODOS os controllers de prévia em cache. Chamado antes de abrir
|
||||
/// um player real (dialog/fullscreen), que já precisa dos seus próprios
|
||||
/// decodificadores de vídeo e áudio — em dispositivos com pouca capacidade
|
||||
/// (sobretudo emuladores), manter qualquer prévia viva ao mesmo tempo é
|
||||
/// suficiente para esgotar os decodificadores e travar o aparelho.
|
||||
void _evictAllVideoControllers() {
|
||||
_videoControllerRefCounts.clear();
|
||||
final controllers = _videoControllerCache.values.toList();
|
||||
_videoControllerCache.clear();
|
||||
for (final controller in controllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> showVideoPlayerDialog(BuildContext context, VideoData video) {
|
||||
if (video.youtubeId != null) {
|
||||
@@ -156,11 +197,9 @@ class _VideoScreenState extends State<VideoScreen> {
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.dispose();
|
||||
// Dispose all cached controllers
|
||||
for (var controller in _videoControllerCache.values) {
|
||||
controller.dispose();
|
||||
}
|
||||
_videoControllerCache.clear();
|
||||
// Não descartamos o cache global aqui: outros widgets (como o cartão em
|
||||
// destaque na Home) podem estar a usar os mesmos controllers. Cada
|
||||
// [VideoThumbnail] liberta a sua própria referência ao ser desmontado.
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -180,7 +219,11 @@ class _VideoScreenState extends State<VideoScreen> {
|
||||
appBar: AppBar(
|
||||
backgroundColor: VideoScreen._teal,
|
||||
foregroundColor: Colors.white,
|
||||
surfaceTintColor: VideoScreen._teal,
|
||||
elevation: 0,
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: kAppBarGradient),
|
||||
),
|
||||
title: const Text(
|
||||
'Videos Educativos',
|
||||
style: TextStyle(fontWeight: FontWeight.w900),
|
||||
@@ -321,9 +364,18 @@ class VideoThumbnail extends StatefulWidget {
|
||||
class _VideoThumbnailState extends State<VideoThumbnail> {
|
||||
VideoPlayerController? _controller;
|
||||
bool _isInitialized = false;
|
||||
bool _hasOwnRef = false;
|
||||
|
||||
bool get _isYoutube => widget.video.youtubeId != null;
|
||||
|
||||
/// Verdadeiro quando outro widget descartou o controller que este
|
||||
/// thumbnail estava a usar (ex.: ao abrir o player em dialog/fullscreen).
|
||||
/// Nesse caso [_controller] deixou de ser o mesmo objeto guardado no
|
||||
/// cache partilhado — nunca é seguro tocar num controller já disposed.
|
||||
bool get _isControllerStale =>
|
||||
_controller != null &&
|
||||
_videoControllerCache[widget.video.videoPath] != _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -332,47 +384,62 @@ class _VideoThumbnailState extends State<VideoThumbnail> {
|
||||
|
||||
Future<void> _initializeVideo() async {
|
||||
final path = widget.video.videoPath!;
|
||||
// Check if controller exists in cache
|
||||
if (_videoControllerCache.containsKey(path)) {
|
||||
_controller = _videoControllerCache[path];
|
||||
await _controller!.seekTo(const Duration(seconds: 2));
|
||||
await _controller!.pause();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isInitialized = true;
|
||||
});
|
||||
final cached = _videoControllerCache[path];
|
||||
if (cached != null) {
|
||||
_controller = cached;
|
||||
_videoControllerRefCounts[path] =
|
||||
(_videoControllerRefCounts[path] ?? 0) + 1;
|
||||
_hasOwnRef = true;
|
||||
try {
|
||||
await cached.seekTo(const Duration(seconds: 2));
|
||||
await cached.pause();
|
||||
if (mounted) setState(() => _isInitialized = true);
|
||||
} catch (_) {
|
||||
// O controller partilhado foi descartado por outra tela entretanto;
|
||||
// larga a referência inválida e cria um novo do zero.
|
||||
_releaseOwnRef();
|
||||
_controller = null;
|
||||
if (mounted) await _createFreshController(path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!_hasThumbnailDecoderSlot) {
|
||||
// Já há decoders suficientes ativos noutras prévias; fica só com o
|
||||
// ícone de play em vez de arriscar sobrecarregar o dispositivo.
|
||||
if (mounted) setState(() => _isInitialized = false);
|
||||
return;
|
||||
}
|
||||
await _createFreshController(path);
|
||||
}
|
||||
|
||||
// Create new controller and cache it
|
||||
_controller = VideoPlayerController.asset(path);
|
||||
Future<void> _createFreshController(String path) async {
|
||||
final controller = VideoPlayerController.asset(path);
|
||||
_controller = controller;
|
||||
try {
|
||||
await _controller!.initialize();
|
||||
await _controller!.seekTo(const Duration(seconds: 2));
|
||||
await _controller!.pause();
|
||||
_videoControllerCache[path] = _controller!;
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isInitialized = true;
|
||||
});
|
||||
}
|
||||
await controller.initialize();
|
||||
await controller.seekTo(const Duration(seconds: 2));
|
||||
await controller.pause();
|
||||
_videoControllerCache[path] = controller;
|
||||
_videoControllerRefCounts[path] =
|
||||
(_videoControllerRefCounts[path] ?? 0) + 1;
|
||||
_hasOwnRef = true;
|
||||
if (mounted) setState(() => _isInitialized = true);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isInitialized = false;
|
||||
});
|
||||
}
|
||||
if (mounted) setState(() => _isInitialized = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _releaseOwnRef() {
|
||||
final path = widget.video.videoPath;
|
||||
if (_hasOwnRef && path != null) {
|
||||
_releaseVideoController(path);
|
||||
_hasOwnRef = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Don't dispose cached controllers, they will be disposed when screen is disposed
|
||||
if (_controller != null &&
|
||||
!_videoControllerCache.containsKey(widget.video.videoPath)) {
|
||||
_controller!.dispose();
|
||||
}
|
||||
_releaseOwnRef();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -406,6 +473,18 @@ class _VideoThumbnailState extends State<VideoThumbnail> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (_isControllerStale) {
|
||||
// Não mexemos no controller antigo (pode já estar disposed); larga a
|
||||
// referência e agenda uma reinicialização para o próximo frame.
|
||||
_hasOwnRef = false;
|
||||
_controller = null;
|
||||
_isInitialized = false;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _initializeVideo();
|
||||
});
|
||||
}
|
||||
|
||||
return _isInitialized && _controller != null
|
||||
? ClipRRect(
|
||||
borderRadius: BorderRadius.circular(widget.borderRadius),
|
||||
@@ -434,11 +513,10 @@ class _VideoButton extends StatelessWidget {
|
||||
final VideoData video;
|
||||
|
||||
void _showVideoPlayer(BuildContext context, VideoData video) {
|
||||
if (video.youtubeId == null &&
|
||||
_videoControllerCache.containsKey(video.videoPath)) {
|
||||
// Dispose the cached controller to avoid codec conflict with dialog controller
|
||||
_videoControllerCache[video.videoPath]!.dispose();
|
||||
_videoControllerCache.remove(video.videoPath);
|
||||
if (video.youtubeId == null) {
|
||||
// Liberta todos os decodificadores de prévia antes de abrir o player
|
||||
// em dialog, que precisa dos seus próprios decoders de vídeo/áudio.
|
||||
_evictAllVideoControllers();
|
||||
}
|
||||
showVideoPlayerDialog(context, video);
|
||||
}
|
||||
@@ -696,6 +774,15 @@ class _VideoControlsState extends State<_VideoControls> {
|
||||
}
|
||||
}
|
||||
|
||||
void _seekBy(Duration offset) {
|
||||
final position = widget.controller.value.position;
|
||||
final duration = widget.controller.value.duration;
|
||||
var target = position + offset;
|
||||
if (target < Duration.zero) target = Duration.zero;
|
||||
if (target > duration) target = duration;
|
||||
widget.controller.seekTo(target);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
@@ -723,6 +810,15 @@ class _VideoControlsState extends State<_VideoControls> {
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.replay_10_rounded,
|
||||
color: Colors.white,
|
||||
),
|
||||
tooltip: 'Retroceder 10s',
|
||||
onPressed: () =>
|
||||
_seekBy(const Duration(seconds: -10)),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
widget.controller.value.isPlaying
|
||||
@@ -738,16 +834,20 @@ class _VideoControlsState extends State<_VideoControls> {
|
||||
}
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.forward_10_rounded,
|
||||
color: Colors.white,
|
||||
),
|
||||
tooltip: 'Avançar 10s',
|
||||
onPressed: () => _seekBy(const Duration(seconds: 10)),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.fullscreen, color: Colors.white),
|
||||
onPressed: () {
|
||||
// Dispose the cached controller to avoid codec conflict with fullscreen controller
|
||||
if (_videoControllerCache.containsKey(
|
||||
widget.videoPath,
|
||||
)) {
|
||||
_videoControllerCache[widget.videoPath]!.dispose();
|
||||
_videoControllerCache.remove(widget.videoPath);
|
||||
}
|
||||
// Liberta todos os decodificadores de prévia antes
|
||||
// de abrir o player em fullscreen.
|
||||
_evictAllVideoControllers();
|
||||
Navigator.of(context).pop();
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
@@ -826,6 +926,15 @@ class _FullscreenVideoPlayerState extends State<_FullscreenVideoPlayer> {
|
||||
}
|
||||
}
|
||||
|
||||
void _seekBy(Duration offset) {
|
||||
final position = _controller.value.position;
|
||||
final duration = _controller.value.duration;
|
||||
var target = position + offset;
|
||||
if (target < Duration.zero) target = Duration.zero;
|
||||
if (target > duration) target = duration;
|
||||
_controller.seekTo(target);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
@@ -854,20 +963,49 @@ class _FullscreenVideoPlayerState extends State<_FullscreenVideoPlayer> {
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (_isInitialized)
|
||||
FloatingActionButton(
|
||||
heroTag: 'play_pause',
|
||||
backgroundColor: VideoScreen._teal,
|
||||
onPressed: () {
|
||||
if (_controller.value.isPlaying) {
|
||||
_controller.pause();
|
||||
} else {
|
||||
_controller.play();
|
||||
}
|
||||
},
|
||||
child: Icon(
|
||||
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
|
||||
color: Colors.white,
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
FloatingActionButton(
|
||||
heroTag: 'rewind',
|
||||
mini: true,
|
||||
backgroundColor: VideoScreen._teal,
|
||||
onPressed: () => _seekBy(const Duration(seconds: -10)),
|
||||
child: const Icon(
|
||||
Icons.replay_10_rounded,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
FloatingActionButton(
|
||||
heroTag: 'play_pause',
|
||||
backgroundColor: VideoScreen._teal,
|
||||
onPressed: () {
|
||||
if (_controller.value.isPlaying) {
|
||||
_controller.pause();
|
||||
} else {
|
||||
_controller.play();
|
||||
}
|
||||
},
|
||||
child: Icon(
|
||||
_controller.value.isPlaying
|
||||
? Icons.pause
|
||||
: Icons.play_arrow,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
FloatingActionButton(
|
||||
heroTag: 'forward',
|
||||
mini: true,
|
||||
backgroundColor: VideoScreen._teal,
|
||||
onPressed: () => _seekBy(const Duration(seconds: 10)),
|
||||
child: const Icon(
|
||||
Icons.forward_10_rounded,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_isInitialized) const SizedBox(height: 16),
|
||||
FloatingActionButton(
|
||||
|
||||
Reference in New Issue
Block a user