Merge remote-tracking branch 'origin/main' into main

Resolved conflicts by keeping remote functional features (RecordingScheduler,
FFmpeg HLS transcoding, mobile player, channel cards) and restoring local
Stitch theme foundation (app_colors, app_theme, glass_container, mobile_theme).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
MichaelandClaude Opus 4.7 committed 2026-04-27 22:17:52 +02:00
commit 2ba16caf55
68 files changed
+18812 -1794

No files matched your search

+13 -1
View File
@@ -16,12 +16,24 @@ class ApiClient {
connectTimeout: const Duration(seconds: 60),
receiveTimeout: const Duration(seconds: 60),
),);
// Add interceptor for logging
_dio.interceptors.add(LogInterceptor(
requestBody: true,
responseBody: true,
),);
// Restore token from localStorage on initialization
_restoreTokenFromStorage();
}
/// Restore token from localStorage on app startup
void _restoreTokenFromStorage() {
final storedToken = getStoredToken();
if (storedToken != null) {
_token = storedToken;
_dio.options.headers['Authorization'] = 'Bearer $storedToken';
}
}
/// Get base URL (same origin for production)
+323
View File
@@ -0,0 +1,323 @@
/// Application optimization configuration
///
/// This file contains performance tuning settings for XtremFlow
library;
class OptimizationConfig {
// ============================================
// STREAMING OPTIMIZATION
// ============================================
/// Enable adaptive bitrate streaming
static const bool enableAdaptiveBitrate = true;
/// Default quality profile for new streams
static const String defaultQualityResolution = '720x480'; // 480p HD
/// Maximum buffer size in seconds
static const int maxBufferSeconds = 30;
/// Minimum buffer size in seconds before rebuffering
static const int minBufferSeconds = 2;
/// Target buffer size in seconds
static const int targetBufferSeconds = 8;
/// Enable HLS v3 compression
static const bool enableHlsCompression = true;
/// FFmpeg preset for live transcoding
static const String ffmpegLivePreset =
'medium'; // ultrafast, fast, medium, slow
/// FFmpeg preset for VOD transcoding
static const String ffmpegVodPreset = 'medium';
/// Enable NVIDIA GPU acceleration if available
static const bool enableNvidiaGpu = true;
// ============================================
// CACHE OPTIMIZATION
// ============================================
/// Enable aggressive image caching
static const bool enableImageCache = true;
/// Maximum image cache size in MB
static const int maxImageCacheMb = 100;
/// Maximum memory cache size in MB
static const int maxMemoryCacheMb = 200;
/// Cache expiration time in hours
static const int cacheExpirationHours = 24;
/// Enable network cache interceptor
static const bool enableNetworkCache = true;
/// Network cache retention time in days
static const int networkCacheRetentionDays = 3;
// ============================================
// UI OPTIMIZATION
// ============================================
/// Number of items to load per page
static const int itemsPerPage = 50;
/// Number of items per page for Live TV grid view
static const int liveItemsPerPage = 100;
/// Enable lazy loading for content lists
static const bool enableLazyLoading = true;
/// Enable image fade animation on load
static const bool enableImageFadeAnimation = true;
/// Image fade animation duration in milliseconds
static const int imageFadeAnimationMs = 300;
/// Enable smooth scrolling
static const bool enableSmoothScroll = true;
/// TextureView pool size for video rendering (Android)
static const int videoTexturePoolSize = 4;
// ============================================
// NETWORK OPTIMIZATION
// ============================================
/// Connection timeout in seconds
static const int connectionTimeoutSeconds = 30;
/// Receive timeout in seconds
static const int receiveTimeoutSeconds = 60;
/// Max concurrent downloads
static const int maxConcurrentDownloads = 3;
/// Enable network optimization (bandwidth detection, etc)
static const bool enableNetworkOptimization = true;
/// Enable request retry on failure
static const bool enableAutoRetry = true;
/// Max retry attempts
static const int maxRetryAttempts = 3;
/// Enable gzip compression for API requests
static const bool enableGzipCompression = true;
// ============================================
// MEMORY OPTIMIZATION
// ============================================
/// Enable memory profiling on debug builds
static const bool enableMemoryProfiling = false;
/// Collect memory stats every N seconds
static const int memoryProfilingIntervalSeconds = 10;
/// Enable aggressive memory cleanup on app background
static const bool enableMemoryCleanupOnBackground = true;
/// Max number of cached image entries
static const int maxCachedImages = 500;
// ============================================
// PERFORMANCE MONITORING
// ============================================
/// Enable performance monitoring
static const bool enablePerformanceMonitoring = true;
/// Monitor frame rate drops
static const bool monitorFrameRate = true;
/// Frame rate warning threshold (FPS)
static const int frameRateWarningThreshold = 30;
/// Enable network metrics collection
static const bool collectNetworkMetrics = true;
/// Enable streaming quality metrics
static const bool collectStreamingMetrics = true;
// ============================================
// FEATURE FLAGS
// ============================================
/// Enable EPG (Electronic Program Guide)
static const bool enableEpg = true;
/// Enable offline downloads
static const bool enableOfflineDownloads = true;
/// Enable continue watching feature
static const bool enableContinueWatching = true;
/// Enable trending content
static const bool enableTrending = true;
/// Enable adaptive streaming quality selector
static const bool enableQualitySelector = true;
/// Enable subtitle support
static const bool enableSubtitles = true;
/// Enable watch history tracking
static const bool enableWatchHistory = true;
/// Enable user favorites
static const bool enableFavorites = true;
// ============================================
// HELPER METHODS
// ============================================
/// Get optimized image cache settings
static Map<String, dynamic> getImageCacheSettings() => {
'maxSize': maxImageCacheMb * 1024 * 1024,
'maxItems': maxCachedImages,
'enableAnimation': enableImageFadeAnimation,
'fadeAnimationMs': imageFadeAnimationMs,
};
/// Get streaming configuration
static Map<String, dynamic> getStreamingConfig() => {
'enableAdaptiveBitrate': enableAdaptiveBitrate,
'defaultQuality': defaultQualityResolution,
'maxBuffer': maxBufferSeconds,
'minBuffer': minBufferSeconds,
'targetBuffer': targetBufferSeconds,
'enableHlsCompression': enableHlsCompression,
'ffmpegPreset': ffmpegLivePreset,
'enableGpu': enableNvidiaGpu,
};
/// Get network configuration
static Map<String, dynamic> getNetworkConfig() => {
'connectTimeout': connectionTimeoutSeconds,
'receiveTimeout': receiveTimeoutSeconds,
'enableAutoRetry': enableAutoRetry,
'maxRetries': maxRetryAttempts,
'enableGzip': enableGzipCompression,
'enableCache': enableNetworkCache,
'cacheRetentionDays': networkCacheRetentionDays,
};
/// Get UI performance settings
static Map<String, dynamic> getUiPerformanceSettings() => {
'itemsPerPage': itemsPerPage,
'liveItemsPerPage': liveItemsPerPage,
'enableLazyLoading': enableLazyLoading,
'enableSmoothScroll': enableSmoothScroll,
'maxTexturePoolSize': videoTexturePoolSize,
};
/// Get memory optimization settings
static Map<String, dynamic> getMemoryOptimizationSettings() => {
'enableProfiling': enableMemoryProfiling,
'profilingInterval': memoryProfilingIntervalSeconds,
'aggressiveCleanup': enableMemoryCleanupOnBackground,
'maxImageCacheMb': maxImageCacheMb,
'maxMemoryCacheMb': maxMemoryCacheMb,
};
/// Get all enabled features
static List<String> getEnabledFeatures() => [
if (enableEpg) 'EPG',
if (enableOfflineDownloads) 'OfflineDownloads',
if (enableContinueWatching) 'ContinueWatching',
if (enableTrending) 'Trending',
if (enableQualitySelector) 'QualitySelector',
if (enableSubtitles) 'Subtitles',
if (enableWatchHistory) 'WatchHistory',
if (enableFavorites) 'Favorites',
];
/// Print configuration summary
static void printSummary() {
print('''
╔════════════════════════════════════════════════════════════╗
║ XtremFlow Optimization Configuration ║
╠════════════════════════════════════════════════════════════╣
║ STREAMING ║
║ • Adaptive Bitrate: $enableAdaptiveBitrate ║
║ • Default Quality: $defaultQualityResolution ║
║ • GPU Acceleration: $enableNvidiaGpu ║
║ ║
║ CACHE ║
║ • Image Cache: ${maxImageCacheMb}MB ║
║ • Memory Cache: ${maxMemoryCacheMb}MB ║
║ • Network Cache: $enableNetworkCache ║
║ ║
║ NETWORK ║
║ • Connection Timeout: ${connectionTimeoutSeconds}s ║
║ • Auto Retry: $enableAutoRetry ║
║ • Max Retries: $maxRetryAttempts ║
║ ║
║ FEATURES ENABLED: ${getEnabledFeatures().join(', ')}║
║ ║
╚════════════════════════════════════════════════════════════╝
''');
}
}
/// Runtime optimization flags
class RuntimeOptimizations {
static bool hasHighPerformanceDevice = false;
static bool isLowBatteryMode = false;
static bool isLowMemoryMode = false;
static int availableMemoryMb = 0;
static int availableStorageMb = 0;
/// Adjust settings based on device capabilities
static void calibrateForDevice({
required int totalMemoryMb,
required int freeMemoryMb,
required int storageFreeMb,
}) {
availableMemoryMb = freeMemoryMb;
availableStorageMb = storageFreeMb;
// Detect low memory condition
isLowMemoryMode = freeMemoryMb < 500;
// Detect low storage
if (storageFreeMb < 1000) {
print(
'[WARNING] Low storage available: ${storageFreeMb}MB. Disabling offline downloads.',
);
}
// High performance device detection
hasHighPerformanceDevice = totalMemoryMb > 4000 && storageFreeMb > 5000;
print(
'[Device Calibration] Memory: ${freeMemoryMb}MB, Storage: ${storageFreeMb}MB',
);
}
/// Get dynamic cache size based on available memory
static int getDynamicCacheSize() {
if (isLowMemoryMode) {
return 50; // 50MB on low memory devices
}
if (hasHighPerformanceDevice) {
return 200; // 200MB on high performance devices
}
return OptimizationConfig.maxMemoryCacheMb;
}
/// Get dynamic image cache size
static int getDynamicImageCacheSize() {
if (isLowMemoryMode) {
return 30; // 30MB
}
if (hasHighPerformanceDevice) {
return 150; // 150MB
}
return OptimizationConfig.maxImageCacheMb;
}
}
@@ -0,0 +1,346 @@
/// Adaptive Bitrate (ABR) Streaming Handler for HLS
///
/// Supports multi-bitrate HLS playlists for adaptive streaming
/// with fallback options for poor network conditions
library;
/// Represents a video quality level for adaptive bitrate streaming
class QualityLevel {
final String resolution;
final int bitrateBps;
final int width;
final int height;
final String ffmpegPreset; // ultrafast, fast, medium, slow
final String label;
const QualityLevel({
required this.resolution,
required this.bitrateBps,
required this.width,
required this.height,
this.ffmpegPreset = 'medium',
required this.label,
});
/// Get FFmpeg video bitrate argument
String get videoBitrateArg => '${(bitrateBps * 0.75).toInt() ~/ 1000}k';
/// Get FFmpeg maxrate argument (150% of bitrate)
String get maxRateArg => '${((bitrateBps * 1.5).toInt() ~/ 1000)}k';
/// Get FFmpeg buffer size argument
String get bufferSizeArg => '${((bitrateBps * 2).toInt() ~/ 1000)}k';
@override
String toString() => '$label ($resolution - ${bitrateBps ~/ 1000000}Mbps)';
}
/// Standard quality profiles for adaptive streaming
class QualityProfiles {
// Mobile & Low Bandwidth
static const mobile240p = QualityLevel(
resolution: '426x240',
bitrateBps: 500000, // 0.5 Mbps
width: 426,
height: 240,
ffmpegPreset: 'ultrafast',
label: '240p (Low)',
);
static const mobile360p = QualityLevel(
resolution: '640x360',
bitrateBps: 1200000, // 1.2 Mbps
width: 640,
height: 360,
ffmpegPreset: 'ultrafast',
label: '360p (Mobile)',
);
// Standard Quality
static const hd480p = QualityLevel(
resolution: '854x480',
bitrateBps: 2500000, // 2.5 Mbps
width: 854,
height: 480,
ffmpegPreset: 'fast',
label: '480p (SD)',
);
static const hd720p = QualityLevel(
resolution: '1280x720',
bitrateBps: 5000000, // 5 Mbps
width: 1280,
height: 720,
ffmpegPreset: 'medium',
label: '720p (HD)',
);
// High Quality
static const fhd1080p = QualityLevel(
resolution: '1920x1080',
bitrateBps: 8000000, // 8 Mbps
width: 1920,
height: 1080,
ffmpegPreset: 'medium',
label: '1080p (Full HD)',
);
// Ultra HD
static const uhd2k = QualityLevel(
resolution: '2560x1440',
bitrateBps: 15000000, // 15 Mbps
width: 2560,
height: 1440,
ffmpegPreset: 'slow',
label: '2K (QHD)',
);
static const uhd4k = QualityLevel(
resolution: '3840x2160',
bitrateBps: 25000000, // 25 Mbps
width: 3840,
height: 2160,
ffmpegPreset: 'slow',
label: '4K',
);
/// Get default profiles for balanced streaming
static List<QualityLevel> getBalancedProfiles() => [
mobile240p,
mobile360p,
hd480p,
hd720p,
fhd1080p,
];
/// Get all available profiles
static List<QualityLevel> getAllProfiles() => [
mobile240p,
mobile360p,
hd480p,
hd720p,
fhd1080p,
uhd2k,
uhd4k,
];
/// Get profiles suitable for streaming type
static List<QualityLevel> getProfiles({
required String type, // 'live', 'vod', 'low-bandwidth'
int? maxBitrateBps,
}) {
List<QualityLevel> profiles = getBalancedProfiles();
// Filter by streaming type
if (type == 'live') {
// Live TV prefers lower bitrates for stability
profiles = [mobile240p, mobile360p, hd480p, hd720p];
} else if (type == 'low-bandwidth') {
// Mobile/low bandwidth - only lower profiles
profiles = [mobile240p, mobile360p, hd480p];
}
// Filter by max bitrate if specified
if (maxBitrateBps != null) {
profiles = profiles.where((p) => p.bitrateBps <= maxBitrateBps).toList();
}
// Ensure at least one profile
if (profiles.isEmpty) {
profiles = [mobile240p];
}
return profiles;
}
}
/// Bandwidth detector for adaptive bitrate selection
class BandwidthDetector {
final _samples = <DateTime, int>{}; // timestamp -> bytes downloaded
final int _totalBytesLastPeriod = 0;
final Duration _sampleWindow = const Duration(seconds: 10);
/// Record bytes downloaded at current time
void recordBytes(int bytes) {
final now = DateTime.now();
_samples[now] = bytes;
// Clean up old samples
final cutoff = now.subtract(_sampleWindow);
_samples.removeWhere((time, _) => time.isBefore(cutoff));
}
/// Estimate current bandwidth in bps
int estimateBandwidthBps() {
if (_samples.isEmpty) return 0;
int totalBytes = 0;
for (var bytes in _samples.values) {
totalBytes += bytes;
}
final timeSpan = DateTime.now()
.difference(
_samples.keys.reduce((a, b) => a.isBefore(b) ? a : b),
)
.inMilliseconds;
if (timeSpan == 0) return 0;
// bytes per second * 8 = bits per second
return ((totalBytes / (timeSpan / 1000)) * 8).toInt();
}
/// Get estimated bandwidth in Mbps
double estimateBandwidthMbps() {
return estimateBandwidthBps() / 1000000;
}
/// Select best quality level based on bandwidth
static QualityLevel selectBestQuality(
int bandwidthBps,
List<QualityLevel> availableProfiles,
) {
// Use 75% of detected bandwidth for conservative selection
final targetBitrate = (bandwidthBps * 0.75).toInt();
// Find highest quality that fits our bandwidth
var best = availableProfiles[0];
for (final profile in availableProfiles) {
if (profile.bitrateBps <= targetBitrate) {
best = profile;
} else {
break;
}
}
return best;
}
}
/// Master playlist generator for HLS variant streams
class HlsMasterPlaylistGenerator {
/// Generate M3U8 master playlist with multiple quality variants
static String generateMasterPlaylist({
required List<QualityLevel> qualityLevels,
required String baseUrl,
bool includeSubtitles = false,
}) {
final buffer = StringBuffer();
// HLS version 3 for compatibility
buffer.writeln('#EXTM3U');
buffer.writeln('#EXT-X-VERSION:3');
buffer.writeln('#EXT-X-TARGET-DURATION:10');
buffer.writeln('#EXT-X-MEDIA-SEQUENCE:0');
// Variant streams (quality levels)
for (final quality in qualityLevels) {
buffer.writeln('#EXT-X-STREAM-INF:BANDWIDTH=${quality.bitrateBps},'
'RESOLUTION=${quality.width}x${quality.height}');
buffer
.writeln('$baseUrl/variant_${quality.width}x${quality.height}.m3u8');
}
return buffer.toString();
}
/// Generate variant playlist for specific quality level
static String generateVariantPlaylist({
required String segmentPrefix,
required int totalSegments,
required double targetDuration,
required bool isFinal,
}) {
final buffer = StringBuffer();
buffer.writeln('#EXTM3U');
buffer.writeln('#EXT-X-VERSION:3');
buffer.writeln('#EXT-X-TARGET-DURATION:${targetDuration.ceil()}');
buffer.writeln('#EXT-X-MEDIA-SEQUENCE:0');
// Add segment entries
for (int i = 0; i < totalSegments; i++) {
buffer.writeln('#EXTINF:$targetDuration,');
buffer.writeln('${segmentPrefix}_$i.ts');
}
if (isFinal) {
buffer.writeln('#EXT-X-ENDLIST');
}
return buffer.toString();
}
}
/// Quality selector based on network conditions
class QualitySelector {
final _detector = BandwidthDetector();
QualityLevel _currentQuality;
final _listeners = <VoidCallback>[];
QualitySelector({
required QualityLevel initialQuality,
}) : _currentQuality = initialQuality;
QualityLevel get currentQuality => _currentQuality;
/// Record bandwidth and auto-adjust quality
void recordBandwidth(int bytesDownloaded) {
_detector.recordBytes(bytesDownloaded);
// Check if we should switch quality
_maybeAdjustQuality();
}
/// Manually set quality
void setQuality(QualityLevel quality) {
if (_currentQuality != quality) {
_currentQuality = quality;
_notifyListeners();
}
}
/// Force rebuffer wait before switching down
void rebufferDetected() {
// Switch to lower quality if rebuffering occurs
final allProfiles = QualityProfiles.getAllProfiles();
final currentIndex = allProfiles.indexOf(_currentQuality);
if (currentIndex > 0) {
setQuality(allProfiles[currentIndex - 1]);
}
}
void _maybeAdjustQuality() {
final bandwidthBps = _detector.estimateBandwidthBps();
final availableProfiles = QualityProfiles.getBalancedProfiles();
// Only switch if significantly different from current
final overhead = _currentQuality.bitrateBps * 1.2;
if (bandwidthBps > overhead ||
bandwidthBps < _currentQuality.bitrateBps * 0.5) {
final bestQuality =
BandwidthDetector.selectBestQuality(bandwidthBps, availableProfiles);
setQuality(bestQuality);
}
}
void addListener(VoidCallback listener) {
_listeners.add(listener);
}
void removeListener(VoidCallback listener) {
_listeners.remove(listener);
}
void _notifyListeners() {
for (final listener in _listeners) {
listener();
}
}
double getEstimatedBandwidthMbps() => _detector.estimateBandwidthMbps();
}
// Type alias for void callback
typedef VoidCallback = void Function();
+224
View File
@@ -0,0 +1,224 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
/// Cache entry with metadata
class CacheEntry<T> {
final T data;
final DateTime timestamp;
final int sizeEstimate;
int accessCount;
DateTime lastAccess;
CacheEntry({
required this.data,
required this.sizeEstimate,
}) : timestamp = DateTime.now(),
lastAccess = DateTime.now(),
accessCount = 0;
bool isExpired({Duration ttl = const Duration(hours: 24)}) {
return DateTime.now().difference(timestamp) > ttl;
}
void markAccess() {
accessCount++;
lastAccess = DateTime.now();
}
}
/// Optimized cache service for memory management
class CacheService {
static const _maxMemoryCacheSizeMb = 200;
static const _maxImageCacheItems = 500;
final Map<String, CacheEntry> _cache = {};
int _totalSizeBytes = 0;
/// Cache data with automatic size management
void cache<T>(String key, T value, {int estimatedSize = 1000}) {
// Remove old entry if exists
if (_cache.containsKey(key)) {
_totalSizeBytes -= _cache[key]!.sizeEstimate;
}
_cache[key] = CacheEntry(
data: value,
sizeEstimate: estimatedSize,
);
_totalSizeBytes += estimatedSize;
// Trim cache if over size limit
_trimCacheIfNeeded();
}
/// Get cached data
T? get<T>(String key) {
final entry = _cache[key];
if (entry != null && !entry.isExpired()) {
entry.markAccess();
return entry.data as T;
}
return null;
}
/// Check if key exists and is valid
bool has(String key) {
final entry = _cache[key];
return entry != null && !entry.isExpired();
}
/// Get cache stats
Map<String, dynamic> getStats() => {
'totalSize': _totalSizeBytes,
'totalSizeMb': _totalSizeBytes / (1024 * 1024),
'itemCount': _cache.length,
'averageSizePerItem':
_cache.isEmpty ? 0 : _totalSizeBytes ~/ _cache.length,
};
/// Clear all cache
void clear() {
_cache.clear();
_totalSizeBytes = 0;
}
/// Clear expired entries
void clearExpired() {
final now = DateTime.now();
final toRemove = _cache.entries
.where((e) => e.value.isExpired())
.map((e) => e.key)
.toList();
for (final key in toRemove) {
_totalSizeBytes -= _cache[key]!.sizeEstimate;
_cache.remove(key);
}
}
/// Trim cache by removing least recently used entries
void _trimCacheIfNeeded() {
const maxSize = _maxMemoryCacheSizeMb * 1024 * 1024;
if (_totalSizeBytes > maxSize) {
// Remove least recently accessed entries
final sorted = _cache.entries.toList()
..sort((a, b) => a.value.accessCount.compareTo(b.value.accessCount));
for (final entry in sorted) {
if (_totalSizeBytes <= maxSize * 0.8) break;
_totalSizeBytes -= entry.value.sizeEstimate;
_cache.remove(entry.key);
}
}
}
}
/// Cached image metadata
class CachedImage {
final String url;
final int sizeBytes;
final DateTime cachedAt;
int accessCount = 0;
CachedImage({
required this.url,
required this.sizeBytes,
}) : cachedAt = DateTime.now();
}
/// Image cache with size limiting
class ImageCacheManager {
static const _maxImageMemoryMb = 100;
static const _maxImages = 500;
final Map<String, CachedImage> _imageCache = {};
int _totalMemoryBytes = 0;
/// Add image to cache
void cacheImage(String url, int sizeEstimateBytes) {
if (_imageCache.length >= _maxImages) {
_evictLeastUsed();
}
_imageCache[url] = CachedImage(
url: url,
sizeBytes: sizeEstimateBytes,
);
_totalMemoryBytes += sizeEstimateBytes;
// Trim if over size
while (_totalMemoryBytes > _maxImageMemoryMb * 1024 * 1024) {
_evictLeastUsed();
}
}
/// Check if image is cached
bool isCached(String url) => _imageCache.containsKey(url);
/// Mark image as accessed
void markAccessed(String url) {
if (_imageCache.containsKey(url)) {
_imageCache[url]!.accessCount++;
}
}
/// Evict least used image
void _evictLeastUsed() {
if (_imageCache.isEmpty) return;
final leastUsed = _imageCache.entries
.reduce((a, b) => a.value.accessCount < b.value.accessCount ? a : b);
_totalMemoryBytes -= leastUsed.value.sizeBytes;
_imageCache.remove(leastUsed.key);
}
/// Get cache stats
Map<String, dynamic> getStats() => {
'totalMemoryMb': _totalMemoryBytes / (1024 * 1024),
'cachedImages': _imageCache.length,
'maxImages': _maxImages,
};
/// Clear all image cache
void clear() {
_imageCache.clear();
_totalMemoryBytes = 0;
}
}
// Riverpod providers
final cacheServiceProvider = Provider<CacheService>((ref) {
return CacheService();
});
final imageCacheManagerProvider = Provider<ImageCacheManager>((ref) {
return ImageCacheManager();
});
/// Provider for cache statistics
final cacheStatsProvider =
StateNotifierProvider<CacheStatsNotifier, Map<String, dynamic>>((ref) {
final cacheService = ref.watch(cacheServiceProvider);
return CacheStatsNotifier(cacheService);
});
class CacheStatsNotifier extends StateNotifier<Map<String, dynamic>> {
final CacheService _cacheService;
CacheStatsNotifier(this._cacheService) : super(_cacheService.getStats());
void refreshStats() {
state = _cacheService.getStats();
}
void clearCache() {
_cacheService.clear();
state = _cacheService.getStats();
}
void clearExpired() {
_cacheService.clearExpired();
state = _cacheService.getStats();
}
}
+287
View File
@@ -0,0 +1,287 @@
import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:io';
/// Advanced network configuration for streaming
class NetworkConfig {
final String? proxyUrl;
final String? userAgent;
final Map<String, String> customHeaders;
final Duration connectTimeout;
final Duration receiveTimeout;
final bool enableValidateSSL;
const NetworkConfig({
this.proxyUrl,
this.userAgent = 'VLC/3.0.18 LibVLC/3.0.18',
this.customHeaders = const {},
this.connectTimeout = const Duration(seconds: 30),
this.receiveTimeout = const Duration(seconds: 60),
this.enableValidateSSL = true,
});
NetworkConfig copyWith({
String? proxyUrl,
String? userAgent,
Map<String, String>? customHeaders,
Duration? connectTimeout,
Duration? receiveTimeout,
bool? enableValidateSSL,
}) =>
NetworkConfig(
proxyUrl: proxyUrl ?? this.proxyUrl,
userAgent: userAgent ?? this.userAgent,
customHeaders: customHeaders ?? this.customHeaders,
connectTimeout: connectTimeout ?? this.connectTimeout,
receiveTimeout: receiveTimeout ?? this.receiveTimeout,
enableValidateSSL: enableValidateSSL ?? this.enableValidateSSL,
);
}
/// Advanced network service with proxy and optimization support
class OptimizedNetworkService {
late Dio _dio;
late NetworkConfig _config;
late CacheInterceptor _cacheInterceptor;
OptimizedNetworkService({required NetworkConfig config}) {
_config = config;
_initializeDio();
}
void _initializeDio() {
_cacheInterceptor = CacheInterceptor(
options: CacheOptions(
store: MemCacheStore(),
policy: CachePolicy.requestFirst,
hitCacheOnErrorExcept: [],
allowPostMethod: false,
),
);
_dio = Dio(
BaseOptions(
connectTimeout: _config.connectTimeout,
receiveTimeout: _config.receiveTimeout,
validateStatus: (status) => status != null && status < 500,
headers: {
'User-Agent': _config.userAgent,
..._config.customHeaders,
},
),
);
// Configure proxy if specified
if (_config.proxyUrl != null) {
_configureProxy(_config.proxyUrl!);
}
// Add interceptors
_dio.interceptors.addAll([
_cacheInterceptor,
_BandwidthTrackingInterceptor(),
_RetryInterceptor(),
]);
}
/// Configure native Dart HttpClient with proxy
void _configureProxy(String proxyUrl) {
try {
final uri = Uri.parse(proxyUrl);
_dio.httpClientAdapter = HttpClientAdapter(
onHttpClientCreate: (client) {
client.findProxy = (uri) {
return 'PROXY ${uri.host}:${uri.port}';
};
return client;
},
);
} catch (e) {
print('Error configuring proxy: $e');
}
}
/// Update network configuration
void updateConfig(NetworkConfig config) {
_config = config;
_initializeDio();
}
Dio get dio => _dio;
/// Download file with resume support
Future<void> downloadFile({
required String url,
required String savePath,
required Function(int, int) onProgress,
CancelToken? cancelToken,
}) async {
try {
await _dio.download(
url,
savePath,
onReceiveProgress: onProgress,
cancelToken: cancelToken,
options: Options(
headers: {'Range': 'bytes=0-'},
),
);
} catch (e) {
rethrow;
}
}
/// Stream request with large response handling
Future<void> streamRequest({
required String url,
required Function(List<int>) onData,
required VoidCallback onDone,
required Function(dynamic) onError,
CancelToken? cancelToken,
}) async {
try {
final response = await _dio.get<ResponseBody>(
url,
options: Options(
responseType: ResponseType.stream,
receiveTimeout: const Duration(minutes: 5),
),
cancelToken: cancelToken,
);
final stream = response.data?.stream;
if (stream != null) {
stream.listen(
onData,
onError: onError,
onDone: onDone,
);
}
} catch (e) {
onError(e);
}
}
/// Clear cache
void clearCache() {
_cacheInterceptor.clearCache();
}
}
/// Interceptor for tracking bandwidth
class _BandwidthTrackingInterceptor extends Interceptor {
int _bytesReceived = 0;
DateTime _lastReset = DateTime.now();
int get bytesReceivedLastSecond {
final now = DateTime.now();
final secondsElapsed = now.difference(_lastReset).inSeconds;
if (secondsElapsed > 1) {
final bps = _bytesReceived ~/ secondsElapsed;
_bytesReceived = 0;
_lastReset = now;
return bps;
}
return 0;
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
if (response.data is ResponseBody) {
// Track bytes for streaming responses
} else if (response.data is List<int>) {
_bytesReceived += (response.data as List<int>).length;
}
handler.next(response);
}
}
/// Interceptor for automatic retry on failure
class _RetryInterceptor extends Interceptor {
static const _maxRetries = 3;
@override
Future<void> onError(
DioException err,
ErrorInterceptorHandler handler,
) async {
// Only retry on timeout or connection errors
if (err.type == DioExceptionType.connectionTimeout ||
err.type == DioExceptionType.receiveTimeout) {
final requestOptions = err.requestOptions;
int retryCount = requestOptions.extra['retryCount'] ?? 0;
if (retryCount < _maxRetries) {
requestOptions.extra['retryCount'] = retryCount + 1;
// Exponential backoff: 100ms, 200ms, 400ms
final delay = Duration(milliseconds: 100 * (1 << retryCount));
await Future.delayed(delay);
final dio = Dio();
try {
final response = await dio.request<dynamic>(
requestOptions.path,
options: Options(
method: requestOptions.method,
headers: requestOptions.headers,
),
data: requestOptions.data,
queryParameters: requestOptions.queryParameters,
);
return handler.resolve(response);
} on DioException catch (e) {
return handler.next(e);
}
}
}
handler.next(err);
}
}
// Riverpod providers
final networkConfigProvider =
StateNotifierProvider<NetworkConfigNotifier, NetworkConfig>((ref) {
return NetworkConfigNotifier();
});
class NetworkConfigNotifier extends StateNotifier<NetworkConfig> {
NetworkConfigNotifier()
: super(
const NetworkConfig(
userAgent: 'VLC/3.0.18 LibVLC/3.0.18',
),
);
void setProxy(String? proxyUrl) {
state = state.copyWith(proxyUrl: proxyUrl);
}
void setUserAgent(String userAgent) {
state = state.copyWith(userAgent: userAgent);
}
void addCustomHeader(String key, String value) {
final newHeaders = {...state.customHeaders};
newHeaders[key] = value;
state = state.copyWith(customHeaders: newHeaders);
}
void removeCustomHeader(String key) {
final newHeaders = {...state.customHeaders};
newHeaders.remove(key);
state = state.copyWith(customHeaders: newHeaders);
}
void clearCustomHeaders() {
state = state.copyWith(customHeaders: {});
}
}
final networkServiceProvider = Provider<OptimizedNetworkService>((ref) {
final config = ref.watch(networkConfigProvider);
return OptimizedNetworkService(config: config);
});
+21 -20
View File
@@ -5,28 +5,29 @@ import '../models/playlist_config.dart';
class PlaylistApiService {
final ApiClient _api = ApiClient();
/// Get all playlists for current user
/// Get all playlists for current user.
///
/// Throws on API error so the Riverpod [FutureProvider] can expose the
/// [AsyncError] state — ensuring the UI shows a proper error with Retry,
/// instead of silently rendering an empty list.
Future<List<PlaylistConfig>> getPlaylists() async {
try {
final response = await _api.get('/api/playlists');
final data = response.data as Map<String, dynamic>;
final playlistsData = data['playlists'] as List<dynamic>;
final response = await _api.get('/api/playlists');
final data = response.data as Map<String, dynamic>;
final playlistsData = data['playlists'] as List<dynamic>;
return playlistsData.map((p) {
final playlist = p as Map<String, dynamic>;
return PlaylistConfig(
id: playlist['id'] as String,
name: playlist['name'] as String,
dns: playlist['serverUrl'] as String? ?? playlist['dns'] as String,
username: playlist['username'] as String,
password: playlist['password'] as String,
createdAt: DateTime.tryParse(playlist['createdAt'] as String? ?? '') ?? DateTime.now(),
);
}).toList();
} catch (e) {
print('Error fetching playlists: $e');
return [];
}
return playlistsData.map((p) {
final playlist = p as Map<String, dynamic>;
return PlaylistConfig(
id: playlist['id'] as String,
name: playlist['name'] as String,
dns: playlist['serverUrl'] as String? ?? playlist['dns'] as String,
username: playlist['username'] as String,
password: playlist['password'] as String,
createdAt:
DateTime.tryParse(playlist['createdAt'] as String? ?? '') ??
DateTime.now(),
);
}).toList();
}
/// Create a new playlist
+267
View File
@@ -0,0 +1,267 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/services/adaptive_bitrate_service.dart';
/// Video streaming performance metrics
class StreamingMetrics {
final double averageNetworkBitrate;
final double currentNetworkBitrate;
final int bufferDurationMs;
final int segmentDownloadTimeMs;
final int rebufferCount;
final DateTime startTime;
final DateTime? endTime;
StreamingMetrics({
required this.averageNetworkBitrate,
required this.currentNetworkBitrate,
required this.bufferDurationMs,
required this.segmentDownloadTimeMs,
required this.rebufferCount,
required this.startTime,
this.endTime,
});
double get totalPlaybackSeconds =>
(endTime ?? DateTime.now()).difference(startTime).inSeconds.toDouble();
double get qualityScore {
// Score based on metrics
var score = 100.0;
// Penalize for rebuffering
score -= rebufferCount * 10;
// Penalize for low bitrate
if (currentNetworkBitrate < 1000000) score -= 20;
if (currentNetworkBitrate < 500000) score -= 30;
// Reward for smooth playback
if (rebufferCount == 0) score += 10;
return (score).clamp(0, 100);
}
@override
String toString() => '''
StreamingMetrics:
- Avg Bitrate: ${(averageNetworkBitrate / 1000000).toStringAsFixed(2)} Mbps
- Current Bitrate: ${(currentNetworkBitrate / 1000000).toStringAsFixed(2)} Mbps
- Buffer: ${bufferDurationMs}ms
- Segment DL Time: ${segmentDownloadTimeMs}ms
- Rebuffers: $rebufferCount
- Quality Score: ${qualityScore.toStringAsFixed(1)}
- Duration: $totalPlaybackSeconds seconds
''';
}
/// Advanced streaming optimizer
class StreamingOptimizer {
final QualitySelector qualitySelector;
final _metrics = <StreamingMetrics>[];
late StreamingMetrics _currentMetrics;
final StreamController<StreamingMetrics> _metricsController =
StreamController.broadcast();
late Timer _metricsTimer;
final int _segmentStartTime = 0;
int _totalBytesDownloaded = 0;
int _rebufferCount = 0;
int _lastBufferNotificationTime = 0;
StreamingOptimizer({required this.qualitySelector}) {
_initializeMetrics();
_startMetricsCollection();
}
void _initializeMetrics() {
_currentMetrics = StreamingMetrics(
averageNetworkBitrate: 0,
currentNetworkBitrate: 0,
bufferDurationMs: 0,
segmentDownloadTimeMs: 0,
rebufferCount: 0,
startTime: DateTime.now(),
);
}
void _startMetricsCollection() {
_metricsTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
_updateMetrics();
});
}
void _updateMetrics() {
final bandwidthBps = qualitySelector.getEstimatedBandwidthMbps() * 1000000;
_currentMetrics = StreamingMetrics(
averageNetworkBitrate: _totalBytesDownloaded > 0
? (_totalBytesDownloaded * 8 / _currentMetrics.totalPlaybackSeconds)
: 0,
currentNetworkBitrate: bandwidthBps,
bufferDurationMs: _currentMetrics.bufferDurationMs,
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
rebufferCount: _rebufferCount,
startTime: _currentMetrics.startTime,
);
_metrics.add(_currentMetrics);
_metricsController.add(_currentMetrics);
}
/// Record segment download
void recordSegmentDownload(int bytes, Duration downloadTime) {
_totalBytesDownloaded += bytes;
final downloadMs = downloadTime.inMilliseconds;
_currentMetrics = _currentMetrics;
qualitySelector.recordBandwidth(bytes);
}
/// Handle rebuffer event
void rebufferDetected(Duration duration) {
_rebufferCount++;
_lastBufferNotificationTime = DateTime.now().millisecondsSinceEpoch;
_currentMetrics = StreamingMetrics(
averageNetworkBitrate: _currentMetrics.averageNetworkBitrate,
currentNetworkBitrate: _currentMetrics.currentNetworkBitrate,
bufferDurationMs: duration.inMilliseconds,
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
rebufferCount: _rebufferCount,
startTime: _currentMetrics.startTime,
);
// Auto downgrade quality on rebuffer
qualitySelector.rebufferDetected();
}
/// Get current streaming metrics
StreamingMetrics getMetrics() => _currentMetrics;
/// Get metrics stream for real-time monitoring
Stream<StreamingMetrics> get metricsStream => _metricsController.stream;
/// Get metrics history
List<StreamingMetrics> getMetricsHistory() => List.from(_metrics);
/// Finalize streaming session
void finalize() {
_currentMetrics = StreamingMetrics(
averageNetworkBitrate: _currentMetrics.averageNetworkBitrate,
currentNetworkBitrate: _currentMetrics.currentNetworkBitrate,
bufferDurationMs: _currentMetrics.bufferDurationMs,
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
rebufferCount: _rebufferCount,
startTime: _currentMetrics.startTime,
endTime: DateTime.now(),
);
}
/// Clean up resources
void dispose() {
_metricsTimer.cancel();
_metricsController.close();
}
}
/// Buffer size calculator for adaptive streaming
class BufferCalculator {
static const _minBufferMs = 1000; // 1 second
static const _targetBufferMs = 8000; // 8 seconds
static const _maxBufferMs = 30000; // 30 seconds
/// Calculate optimal buffer size based on bandwidth
static int calculateOptimalBuffer(
int estimatedBandwidthBps,
int bitrateOfCurrentQuality,
) {
// Rule: buffer should be able to hold 8 seconds worth of content
final neededBytes = (bitrateOfCurrentQuality * _targetBufferMs) ~/ 8000;
final availableBytes = (estimatedBandwidthBps * _targetBufferMs) ~/ 8000;
// If we can't sustain the bitrate + have buffer, reduce target
if (availableBytes < neededBytes) {
return _minBufferMs;
}
// Normal case
return _targetBufferMs;
}
/// Calculate recommended segment duration
static Duration calculateSegmentDuration(int estimatedBandwidthBps) {
if (estimatedBandwidthBps < 500000) {
// Very low bandwidth: shorter segments
return const Duration(seconds: 2);
} else if (estimatedBandwidthBps < 2000000) {
// Low bandwidth
return const Duration(seconds: 4);
} else {
// Good bandwidth
return const Duration(seconds: 6);
}
}
/// Calculate maximum playback quality
static QualityLevel selectQualityForBandwidth(
int estimatedBandwidthBps,
) {
final availableProfiles = QualityProfiles.getBalancedProfiles();
return BandwidthDetector.selectBestQuality(
estimatedBandwidthBps,
availableProfiles,
);
}
}
// Riverpod providers
final streamingOptimizerProvider =
StateNotifierProvider<StreamingOptimizerNotifier, StreamingMetrics>((ref) {
final qualitySelector = ref.watch(qualitySelectorProvider);
return StreamingOptimizerNotifier(qualitySelector);
});
final qualitySelectorProvider = Provider<QualitySelector>((ref) {
return QualitySelector(initialQuality: QualityProfiles.hd720p);
});
class StreamingOptimizerNotifier extends StateNotifier<StreamingMetrics> {
final QualitySelector _qualitySelector;
late StreamingOptimizer _optimizer;
StreamingOptimizerNotifier(this._qualitySelector)
: super(
StreamingMetrics(
averageNetworkBitrate: 0,
currentNetworkBitrate: 0,
bufferDurationMs: 0,
segmentDownloadTimeMs: 0,
rebufferCount: 0,
startTime: DateTime.now(),
),
) {
_optimizer = StreamingOptimizer(qualitySelector: _qualitySelector);
// Listen to metrics updates
_optimizer.metricsStream.listen((metrics) {
state = metrics;
});
}
void recordSegmentDownload(int bytes, Duration duration) {
_optimizer.recordSegmentDownload(bytes, duration);
}
void rebufferDetected(Duration duration) {
_optimizer.rebufferDetected(duration);
}
List<StreamingMetrics> getHistory() => _optimizer.getMetricsHistory();
@override
void dispose() {
_optimizer.dispose();
super.dispose();
}
}
@@ -74,7 +74,7 @@ class _GradientButtonState extends State<GradientButton>
void initState() {
super.initState();
_controller = AnimationController(
duration: AppTheme.durationFast,
duration: AppTheme.durationSm,
vsync: this,
);
_scaleAnimation = Tween<double>(begin: 1.0, end: 0.95).animate(
@@ -365,10 +365,10 @@ class _MediaCardState extends State<MediaCard>
Expanded(
child: AnimatedScale(
scale: _isHovered ? 1.05 : 1.0,
duration: AppTheme.durationFast,
duration: AppTheme.durationSm,
curve: AppTheme.curveDefault,
child: AnimatedContainer(
duration: AppTheme.durationFast,
duration: AppTheme.durationSm,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
color: AppColors.surfaceContainerLow,
+288 -263
View File
@@ -2,8 +2,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../theme/app_colors.dart';
import 'glass_container.dart';
import 'tv_focusable_card.dart';
import '../theme/app_theme.dart';
class HeroCarouselItem {
final String id;
@@ -12,7 +11,8 @@ class HeroCarouselItem {
final String? imageUrl;
final VoidCallback? onTap;
final VoidCallback? onPlay;
final List<String>? badges;
final Color? accentColor;
final String? badge;
HeroCarouselItem({
required this.id,
@@ -21,333 +21,358 @@ class HeroCarouselItem {
this.imageUrl,
this.onTap,
this.onPlay,
this.badges,
this.accentColor,
this.badge,
});
}
class HeroCarousel extends StatefulWidget {
final List<HeroCarouselItem> items;
final bool autoPlay;
final Duration autoPlayInterval;
final double height;
const HeroCarousel({
super.key,
required this.items,
this.autoPlay = true,
this.autoPlayInterval = const Duration(seconds: 6),
this.height = 360,
});
@override
State<HeroCarousel> createState() => _HeroCarouselState();
}
class _HeroCarouselState extends State<HeroCarousel> {
class _HeroCarouselState extends State<HeroCarousel>
with TickerProviderStateMixin {
late PageController _pageController;
late AnimationController _fadeController;
late AnimationController _scaleController;
int _currentIndex = 0;
Timer? _timer;
bool _isHovered = false;
@override
void initState() {
super.initState();
_pageController = PageController();
if (widget.autoPlay) {
_pageController = PageController(
initialPage: 0,
viewportFraction: 1.0,
);
_fadeController = AnimationController(
vsync: this,
duration: AppTheme.durationLg,
);
_scaleController = AnimationController(
vsync: this,
duration: AppTheme.durationXl,
)..repeat(reverse: true);
if (widget.autoPlay && widget.items.isNotEmpty) {
_startAutoPlay();
}
}
@override
void dispose() {
_pageController.dispose();
_fadeController.dispose();
_scaleController.dispose();
_timer?.cancel();
super.dispose();
}
void _startAutoPlay() {
_timer = Timer.periodic(const Duration(seconds: 8), (timer) {
if (_currentIndex < widget.items.length - 1) {
_currentIndex++;
} else {
_currentIndex = 0;
}
if (_pageController.hasClients) {
_timer = Timer.periodic(widget.autoPlayInterval, (timer) {
if (mounted) {
final nextPage = (_currentIndex + 1) % widget.items.length;
_pageController.animateToPage(
_currentIndex,
duration: const Duration(milliseconds: 800),
curve: Curves.fastOutSlowIn,
nextPage,
duration: AppTheme.durationLg,
curve: AppTheme.curveSmooth,
);
}
});
}
@override
void dispose() {
void _stopAutoPlay() {
_timer?.cancel();
_pageController.dispose();
super.dispose();
}
String? _getProxiedUrl(String? url) {
if (url == null || url.isEmpty) return null;
if (url.startsWith('http')) {
return '/api/xtream/$url';
}
return url;
_timer = null;
}
@override
Widget build(BuildContext context) {
if (widget.items.isEmpty) return const SizedBox.shrink();
return SizedBox(
height: 560,
child: Stack(
children: [
PageView.builder(
controller: _pageController,
onPageChanged: (index) {
setState(() => _currentIndex = index);
},
itemCount: widget.items.length,
itemBuilder: (context, index) {
final item = widget.items[index];
return _buildHeroSlide(item);
},
),
// Indicators
Positioned(
bottom: 32,
right: 48,
child: Row(
children: List.generate(
widget.items.length,
(index) => AnimatedContainer(
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.symmetric(horizontal: 4),
width: _currentIndex == index ? 24 : 8,
height: 8,
decoration: BoxDecoration(
color: _currentIndex == index
? AppColors.primaryContainer
: Colors.white.withOpacity(0.3),
borderRadius: BorderRadius.circular(4),
return MouseRegion(
onEnter: (_) {
setState(() => _isHovered = true);
_stopAutoPlay();
},
onExit: (_) {
setState(() => _isHovered = false);
if (widget.autoPlay) {
_startAutoPlay();
}
},
child: SizedBox(
height: widget.height,
child: Stack(
fit: StackFit.expand,
children: [
PageView.builder(
controller: _pageController,
onPageChanged: (index) {
setState(() => _currentIndex = index);
_fadeController.forward(from: 0.0);
},
itemCount: widget.items.length,
itemBuilder: (context, index) {
return _buildCarouselPage(widget.items[index]);
},
),
Positioned(
bottom: 0,
left: 0,
right: 0,
height: 200,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
AppColors.background.withOpacity(0.6),
AppColors.background,
],
),
),
),
),
),
],
Positioned(
bottom: 32,
left: 32,
right: 32,
child: FadeTransition(
opacity: _fadeController,
child: _buildContentOverlay(widget.items[_currentIndex]),
),
),
Positioned(
bottom: 20,
right: 32,
child: _buildIndicators(),
),
],
),
),
);
}
Widget _buildHeroSlide(HeroCarouselItem item) {
Widget _buildCarouselPage(HeroCarouselItem item) {
return Stack(
fit: StackFit.expand,
children: [
// Background Image
if (item.imageUrl != null && item.imageUrl!.isNotEmpty)
Image.network(
_getProxiedUrl(item.imageUrl)!,
item.imageUrl!,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(color: AppColors.surfaceContainerLow),
errorBuilder: (context, error, stackTrace) {
return Container(
color: AppColors.surface,
child: const Center(
child: Icon(Icons.broken_image_outlined, size: 64),
),
);
},
)
else
Container(color: AppColors.surfaceContainerLow),
// Gradient Overlays — Stitch style
Container(color: AppColors.surface),
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
AppColors.baseLevel0.withOpacity(0.4),
AppColors.baseLevel0.withOpacity(0.9),
AppColors.baseLevel0,
],
stops: const [0.0, 0.5, 0.8, 1.0],
),
),
),
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerRight,
end: Alignment.centerLeft,
colors: [
Colors.transparent,
AppColors.baseLevel0.withOpacity(0.8),
AppColors.background.withOpacity(0.3),
AppColors.background.withOpacity(0.8),
],
),
),
),
// Content Info
Padding(
padding: const EdgeInsets.all(48.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Badges row
if (item.badges != null && item.badges!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Wrap(
spacing: 8,
children: item.badges!.map((badge) {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.2),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: AppColors.primary.withOpacity(0.3),
),
),
child: Text(
badge.toUpperCase(),
style: GoogleFonts.inter(
color: AppColors.primary,
fontWeight: FontWeight.w600,
fontSize: 11,
letterSpacing: 0.5,
),
),
);
}).toList(),
),
)
else
Container(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: AppColors.primary.withOpacity(0.2),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: AppColors.primary.withOpacity(0.3),
),
),
child: Text(
'FEATURED',
style: GoogleFonts.inter(
color: AppColors.primary,
fontWeight: FontWeight.w700,
fontSize: 12,
letterSpacing: 1.5,
),
),
),
const SizedBox(height: 16),
// Title
SizedBox(
width: 600,
child: Text(
item.title,
style: GoogleFonts.spaceGrotesk(
fontSize: 48,
fontWeight: FontWeight.w700,
color: AppColors.onSurface,
height: 1.1,
letterSpacing: -0.02,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
if (item.subtitle != null) ...[
const SizedBox(height: 8),
Text(
item.subtitle!,
style: GoogleFonts.inter(
color: AppColors.onSurfaceVariant,
fontSize: 18,
height: 1.5,
),
),
],
const SizedBox(height: 24),
// Actions
Row(
children: [
TvFocusableCard(
onTap: item.onPlay,
borderRadius: 50,
scaleFactor: 1.1,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
decoration: BoxDecoration(
gradient: AppColors.primaryGradient,
borderRadius: BorderRadius.circular(50),
boxShadow: [
BoxShadow(
color: AppColors.primaryContainer.withOpacity(0.4),
blurRadius: 20,
offset: const Offset(0, 5),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.play_arrow_rounded,
color: AppColors.onSurface,
),
const SizedBox(width: 8),
Text(
'WATCH NOW',
style: GoogleFonts.inter(
color: AppColors.onSurface,
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
],
),
),
),
const SizedBox(width: 20),
TvFocusableCard(
onTap: item.onTap,
borderRadius: 50,
child: GlassContainer.glass(
borderRadius: 50,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 16,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.info_outline,
color: AppColors.onSurface,
),
const SizedBox(width: 8),
Text(
'DETAILS',
style: GoogleFonts.inter(
color: AppColors.onSurface,
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
],
),
),
),
],
),
const SizedBox(height: 48),
],
),
),
],
);
}
Widget _buildContentOverlay(HeroCarouselItem item) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (item.badge != null)
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: item.accentColor ?? AppColors.primary,
borderRadius: BorderRadius.circular(AppTheme.radiusSm),
),
child: Text(
item.badge!,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w700,
color: AppColors.primary,
letterSpacing: 0.5,
),
),
),
const SizedBox(height: 12),
Text(
item.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.outfit(
fontSize: 48,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
letterSpacing: -1.0,
height: 1.1,
),
),
if (item.subtitle != null) ...[
const SizedBox(height: 12),
Text(
item.subtitle!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.inter(
fontSize: 16,
fontWeight: FontWeight.w400,
color: AppColors.textSecondary,
height: 1.4,
),
),
],
const SizedBox(height: 24),
if (item.onPlay != null || item.onTap != null)
Row(
children: [
if (item.onPlay != null)
AnimatedScale(
scale: _isHovered ? 1.05 : 1.0,
duration: AppTheme.durationMd,
child: GestureDetector(
onTap: item.onPlay,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
decoration: BoxDecoration(
gradient: AppColors.primaryGradient,
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
boxShadow: [
BoxShadow(
color: (item.accentColor ?? AppColors.primary)
.withOpacity(0.4),
blurRadius: 16,
offset: const Offset(0, 8),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.play_arrow,
color: AppColors.textPrimary,
),
const SizedBox(width: 8),
Text(
'Play',
style: GoogleFonts.inter(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppColors.primary,
),
),
],
),
),
),
),
const SizedBox(width: 16),
if (item.onTap != null)
GestureDetector(
onTap: item.onTap,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
decoration: BoxDecoration(
color: AppColors.surface.withOpacity(0.8),
border: Border.all(
color: AppColors.border,
width: 1.5,
),
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.info_outline,
color: AppColors.textPrimary,
),
const SizedBox(width: 8),
Text(
'More Info',
style: GoogleFonts.inter(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
),
],
),
),
),
],
),
],
);
}
Widget _buildIndicators() {
return Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(
widget.items.length,
(index) => GestureDetector(
onTap: () {
_pageController.animateToPage(
index,
duration: AppTheme.durationMd,
curve: AppTheme.curveDefault,
);
},
child: AnimatedContainer(
duration: AppTheme.durationMd,
curve: AppTheme.curveDefault,
margin: const EdgeInsets.symmetric(horizontal: 6),
width: _currentIndex == index ? 32 : 8,
height: 8,
decoration: BoxDecoration(
color:
_currentIndex == index ? AppColors.primary : AppColors.border,
borderRadius: BorderRadius.circular(4),
),
),
),
),
);
}
}
+144
View File
@@ -0,0 +1,144 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
/// Apple TV Modern Channel Grid
///
/// Responsive grid layout for channels with:
/// - Flexible column count based on screen size
/// - Smooth animations
/// - Focus-aware spacing
class TvChannelGrid extends StatelessWidget {
final List<Widget> children;
final EdgeInsetsGeometry padding;
final double horizontalSpacing;
final double verticalSpacing;
final ScrollController? scrollController;
final ScrollPhysics physics;
const TvChannelGrid({
super.key,
required this.children,
this.padding = const EdgeInsets.fromLTRB(32, 24, 32, 32),
this.horizontalSpacing = 20,
this.verticalSpacing = 20,
this.scrollController,
this.physics = const AlwaysScrollableScrollPhysics(),
});
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
// Guard: during first Flutter Web layout pass, size may be 0 or NaN.
// LayoutBuilder will re-trigger build once the real size is known.
if (screenWidth <= 0 || screenWidth.isNaN || screenWidth.isInfinite) {
return const SizedBox.shrink();
}
// Responsive column count
final int columnCount;
if (screenWidth > 1920) {
columnCount = 6;
} else if (screenWidth > 1600) {
columnCount = 5;
} else if (screenWidth > 1280) {
columnCount = 4;
} else if (screenWidth > 960) {
columnCount = 3;
} else {
columnCount = 2;
}
// Calculate horizontal padding safely using resolved EdgeInsets.
final resolvedPadding = padding.resolve(TextDirection.ltr);
final horizontalPadding = resolvedPadding.left + resolvedPadding.right;
// Compute item width, clamped to avoid negative/NaN values.
final totalSpacing = horizontalSpacing * (columnCount - 1);
final availableWidth = screenWidth - horizontalPadding - totalSpacing;
final itemWidth =
(availableWidth / columnCount).clamp(1.0, double.infinity);
return SingleChildScrollView(
controller: scrollController,
physics: physics,
padding: padding,
child: Wrap(
spacing: horizontalSpacing,
runSpacing: verticalSpacing,
children: [
for (int i = 0; i < children.length; i++)
SizedBox(
width: itemWidth,
child: children[i],
),
],
),
);
}
}
/// Apple TV Modern Horizontal Scrollable List
class TvHorizontalList extends StatelessWidget {
final List<Widget> children;
final String? title;
final EdgeInsetsGeometry padding;
final double itemWidth;
final double spacing;
final ScrollController? scrollController;
const TvHorizontalList({
super.key,
required this.children,
this.title,
this.padding = const EdgeInsets.symmetric(vertical: 16),
this.itemWidth = 200,
this.spacing = 16,
this.scrollController,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Title
if (title != null)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.spacing32,
vertical: AppTheme.spacing16,
),
child: Text(
title!,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
// Horizontal list
SizedBox(
height: 280,
child: ListView.separated(
controller: scrollController,
scrollDirection: Axis.horizontal,
padding: EdgeInsets.symmetric(
horizontal: 32,
// Resolve EdgeInsetsGeometry to a concrete EdgeInsets before
// accessing vertical — casting EdgeInsetsGeometry to double throws.
vertical: padding.resolve(TextDirection.ltr).top,
),
itemCount: children.length,
separatorBuilder: (_, __) => SizedBox(width: spacing),
itemBuilder: (context, index) => SizedBox(
width: itemWidth,
child: children[index],
),
),
),
],
);
}
}
+340
View File
@@ -0,0 +1,340 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:google_fonts/google_fonts.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
import 'glass_container.dart';
/// Apple TV Modern Content Card
///
/// Premium card for displaying movies, shows, or other content with:
/// - Poster image with skeleton loading
/// - Title and metadata
/// - Rating/score display
/// - Interactive hover states
/// - Context menu support
class TvModernCard extends StatefulWidget {
final String id;
final String title;
final String? imageUrl;
final String? rating;
final String? year;
final String? badge;
final Color? badgeColor;
final VoidCallback? onTap;
final VoidCallback? onPlayTap;
final VoidCallback? onMoreTap;
final bool isWatching;
final double? progress;
const TvModernCard({
super.key,
required this.id,
required this.title,
this.imageUrl,
this.rating,
this.year,
this.badge,
this.badgeColor,
this.onTap,
this.onPlayTap,
this.onMoreTap,
this.isWatching = false,
this.progress,
});
@override
State<TvModernCard> createState() => _TvModernCardState();
}
class _TvModernCardState extends State<TvModernCard>
with SingleTickerProviderStateMixin {
bool _isHovered = false;
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: AppTheme.durationMd,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) {
setState(() => _isHovered = true);
_controller.forward();
},
onExit: (_) {
setState(() => _isHovered = false);
_controller.reverse();
},
child: GestureDetector(
onTap: widget.onTap,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// ============ POSTER IMAGE ============
AnimatedScale(
scale: _isHovered ? 1.06 : 1.0,
duration: AppTheme.durationMd,
curve: AppTheme.curveDefault,
child: GlassCard(
borderRadius: AppTheme.radiusLg,
padding: EdgeInsets.zero,
interactive: true,
onTap: widget.onTap,
child: Stack(
fit: StackFit.expand,
children: [
// Poster image
_buildPosterImage(),
// Overlay
if (_isHovered)
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withOpacity(0.7),
],
),
),
),
// Badge
if (widget.badge != null)
Positioned(
top: 12,
right: 12,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: widget.badgeColor ?? AppColors.primary,
borderRadius: BorderRadius.circular(4),
),
child: Text(
widget.badge!,
style: GoogleFonts.inter(
fontSize: 10,
fontWeight: FontWeight.w700,
color: Colors.black,
letterSpacing: 0.5,
),
),
),
),
// Progress indicator (if watching)
if (widget.isWatching && widget.progress != null)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: 3,
decoration: const BoxDecoration(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(AppTheme.radiusLg),
),
),
child: ClipRRect(
borderRadius: const BorderRadius.vertical(
bottom: Radius.circular(AppTheme.radiusLg),
),
child: LinearProgressIndicator(
value: widget.progress,
backgroundColor: AppColors.surfaceVariant,
valueColor: const AlwaysStoppedAnimation(
AppColors.primary,
),
minHeight: 3,
),
),
),
),
// Action buttons (on hover)
if (_isHovered &&
(widget.onPlayTap != null || widget.onMoreTap != null))
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (widget.onPlayTap != null)
_buildActionButton(
icon: Icons.play_arrow,
label: 'Play',
onTap: widget.onPlayTap!,
),
if (widget.onPlayTap != null &&
widget.onMoreTap != null)
const SizedBox(width: 16),
if (widget.onMoreTap != null)
_buildActionButton(
icon: Icons.info_outline,
label: 'Info',
onTap: widget.onMoreTap!,
),
],
),
),
],
),
),
),
const SizedBox(height: 12),
// ============ METADATA ============
// Title
Text(
widget.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
// Rating & Year
if (widget.rating != null || widget.year != null) ...[
const SizedBox(height: 6),
Row(
children: [
if (widget.rating != null) ...[
const Icon(
Icons.star,
size: 14,
color: AppColors.ratingGold,
),
const SizedBox(width: 4),
Text(
widget.rating!,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
],
if (widget.rating != null && widget.year != null)
const SizedBox(width: 12),
if (widget.year != null)
Text(
widget.year!,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w400,
color: AppColors.textTertiary,
),
),
],
),
],
],
),
),
);
}
Widget _buildPosterImage() {
if (widget.imageUrl == null || widget.imageUrl!.isEmpty) {
return Container(
color: AppColors.surface,
child: const Center(
child: Icon(
Icons.image_outlined,
color: AppColors.textSecondary,
size: 48,
),
),
);
}
return CachedNetworkImage(
imageUrl: widget.imageUrl!,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: AppColors.shimmer,
child: const Center(
child: SizedBox(
width: 40,
height: 40,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.primary,
),
),
),
),
errorWidget: (context, url, error) => Container(
color: AppColors.surface,
child: const Center(
child: Icon(
Icons.broken_image_outlined,
color: AppColors.textSecondary,
size: 48,
),
),
),
);
}
Widget _buildActionButton({
required IconData icon,
required String label,
required VoidCallback onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: AppColors.primary,
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
boxShadow: [
BoxShadow(
color: AppColors.primary.withOpacity(0.4),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: Colors.black, size: 18),
const SizedBox(width: 6),
Text(
label,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.black,
),
),
],
),
),
);
}
}
+397
View File
@@ -0,0 +1,397 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
import 'glass_container.dart';
/// Apple TV Modern Top Navigation Bar
///
/// Premium navigation header with:
/// - Logo/branding
/// - Search integration
/// - User menu
/// - Glassmorphism effect
class TvTopNavBar extends StatefulWidget {
final String title;
final VoidCallback? onSearch;
final VoidCallback? onProfile;
final VoidCallback? onNotifications;
final int notificationCount;
final Widget? leading;
final List<Widget>? actions;
const TvTopNavBar({
super.key,
required this.title,
this.onSearch,
this.onProfile,
this.onNotifications,
this.notificationCount = 0,
this.leading,
this.actions,
});
@override
State<TvTopNavBar> createState() => _TvTopNavBarState();
}
class _TvTopNavBarState extends State<TvTopNavBar> {
bool _isHovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => setState(() => _isHovered = true),
onExit: (_) => setState(() => _isHovered = false),
child: GlassContainer(
borderRadius: 0,
hasBorder: false,
showShadow: false,
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.spacing32,
vertical: AppTheme.spacing16,
),
margin: EdgeInsets.zero,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Left: Logo + Title
Row(
children: [
if (widget.leading != null) widget.leading!,
const SizedBox(width: AppTheme.spacing16),
Text(
widget.title,
style: GoogleFonts.outfit(
fontSize: 24,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
letterSpacing: -0.3,
),
),
],
),
// Right: Actions
Row(
children: [
if (widget.onSearch != null) ...[
_buildIconButton(
icon: Icons.search,
onTap: widget.onSearch!,
tooltip: 'Search',
),
const SizedBox(width: AppTheme.spacing16),
],
if (widget.onNotifications != null) ...[
_buildIconButton(
icon: Icons.notifications_none,
onTap: widget.onNotifications!,
tooltip: 'Notifications',
badge: widget.notificationCount > 0
? widget.notificationCount.toString()
: null,
),
const SizedBox(width: AppTheme.spacing16),
],
if (widget.onProfile != null)
_buildIconButton(
icon: Icons.account_circle,
onTap: widget.onProfile!,
tooltip: 'Profile',
),
if (widget.actions != null) ...[
const SizedBox(width: AppTheme.spacing16),
...widget.actions!,
],
],
),
],
),
),
);
}
Widget _buildIconButton({
required IconData icon,
required VoidCallback onTap,
required String tooltip,
String? badge,
}) {
return Tooltip(
message: tooltip,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _isHovered ? AppColors.surface : Colors.transparent,
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
),
child: Stack(
children: [
Icon(
icon,
color: AppColors.textPrimary,
size: 24,
),
if (badge != null)
Positioned(
top: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(4),
decoration: const BoxDecoration(
color: AppColors.error,
shape: BoxShape.circle,
),
child: Text(
badge,
style: GoogleFonts.inter(
fontSize: 10,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
),
),
],
),
),
),
),
);
}
}
/// Apple TV Modern Side Navigation
///
/// Vertical navigation menu with:
/// - Window navigation items
/// - Collapsible menu
/// - Smooth animations
/// - Category grouping
class TvSideNav extends StatefulWidget {
final List<TvNavItem> items;
final int selectedIndex;
final ValueChanged<int> onItemSelected;
final bool expanded;
final VoidCallback? onToggleExpanded;
const TvSideNav({
super.key,
required this.items,
this.selectedIndex = 0,
required this.onItemSelected,
this.expanded = true,
this.onToggleExpanded,
});
@override
State<TvSideNav> createState() => _TvSideNavState();
}
class _TvSideNavState extends State<TvSideNav> {
@override
Widget build(BuildContext context) {
return GlassContainer(
borderRadius: 0,
hasBorder: false,
showShadow: false,
padding: const EdgeInsets.symmetric(vertical: AppTheme.spacing16),
margin: EdgeInsets.zero,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(
widget.items.length,
(index) => _buildNavItem(
item: widget.items[index],
isSelected: index == widget.selectedIndex,
onTap: () => widget.onItemSelected(index),
),
),
),
),
);
}
Widget _buildNavItem({
required TvNavItem item,
required bool isSelected,
required VoidCallback onTap,
}) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.spacing16,
vertical: AppTheme.spacing8,
),
child: GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.spacing16,
vertical: AppTheme.spacing12,
),
decoration: BoxDecoration(
color: isSelected ? AppColors.primary : Colors.transparent,
borderRadius: BorderRadius.circular(AppTheme.radiusMd),
border: !isSelected
? Border.all(color: AppColors.border)
: null,
),
child: Row(
children: [
Icon(
item.icon,
color: isSelected ? Colors.black : AppColors.textSecondary,
size: 20,
),
const SizedBox(width: AppTheme.spacing12),
Expanded(
child: Text(
item.label,
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w600,
color: isSelected ? Colors.black : AppColors.textPrimary,
),
),
),
],
),
),
),
);
}
}
/// Navigation item model
class TvNavItem {
final String label;
final IconData icon;
final String? badge;
TvNavItem({
required this.label,
required this.icon,
this.badge,
});
}
/// Apple TV Modern Floating Action Menu
///
/// Context-aware floating menu with:
/// - Multiple action buttons
/// - Smooth reveal animation
/// - Accessible positioning
class TvFloatingMenu extends StatefulWidget {
final List<TvMenuAction> actions;
final VoidCallback? onClose;
const TvFloatingMenu({
super.key,
required this.actions,
this.onClose,
});
@override
State<TvFloatingMenu> createState() => _TvFloatingMenuState();
}
class _TvFloatingMenuState extends State<TvFloatingMenu>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: AppTheme.durationMd,
)..forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ScaleTransition(
scale: _controller,
child: Container(
padding: const EdgeInsets.all(AppTheme.spacing12),
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(AppTheme.radiusLg),
border: Border.all(color: AppColors.border),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(
widget.actions.length,
(index) => GestureDetector(
onTap: () {
widget.actions[index].onTap?.call();
widget.onClose?.call();
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.spacing16,
vertical: AppTheme.spacing12,
),
child: Row(
children: [
Icon(
widget.actions[index].icon,
color: widget.actions[index].color ?? AppColors.textPrimary,
),
const SizedBox(width: AppTheme.spacing12),
Text(
widget.actions[index].label,
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
],
),
),
),
),
),
),
);
}
}
/// Menu action model
class TvMenuAction {
final String label;
final IconData icon;
final Color? color;
final VoidCallback? onTap;
TvMenuAction({
required this.label,
required this.icon,
this.color,
this.onTap,
});
}