Fixed 3rd person bug

This commit is contained in:
endgame
2025-11-30 23:30:40 +03:00
parent cf96e73253
commit 8d7f788ce2
10 changed files with 655 additions and 383 deletions

View File

@@ -61,6 +61,7 @@ extension ApiServiceChats on ApiService {
"[_sendAuthRequestAfterHandshake] ✅ Профиль и ID пользователя найдены. ID: ${contactProfile['id']}. ЗАПУСКАЕМ АНАЛИТИКУ.", "[_sendAuthRequestAfterHandshake] ✅ Профиль и ID пользователя найдены. ID: ${contactProfile['id']}. ЗАПУСКАЕМ АНАЛИТИКУ.",
); );
_userId = contactProfile['id']; _userId = contactProfile['id'];
await prefs.setString('userId', _userId.toString());
_sessionId = DateTime.now().millisecondsSinceEpoch; _sessionId = DateTime.now().millisecondsSinceEpoch;
_lastActionTime = _sessionId; _lastActionTime = _sessionId;

View File

@@ -102,6 +102,7 @@ class MyApp extends StatelessWidget {
dynamicSchemeVariant: DynamicSchemeVariant.tonalSpot, dynamicSchemeVariant: DynamicSchemeVariant.tonalSpot,
), ),
useMaterial3: true, useMaterial3: true,
pageTransitionsTheme: PageTransitionsTheme(builders: {TargetPlatform.android: CupertinoPageTransitionsBuilder()}),
appBarTheme: AppBarTheme( appBarTheme: AppBarTheme(
titleTextStyle: TextStyle( titleTextStyle: TextStyle(
fontSize: 16, fontSize: 16,
@@ -152,12 +153,14 @@ class MyApp extends StatelessWidget {
navigatorKey: navigatorKey, navigatorKey: navigatorKey,
builder: (context, child) { builder: (context, child) {
final showHud = themeProvider.debugShowPerformanceOverlay; final showHud = themeProvider.debugShowPerformanceOverlay;
if (!showHud) return child ?? const SizedBox.shrink(); return SizedBox.expand(
return Stack( child: Stack(
children: [ children: [
if (child != null) child, if (child != null) child,
if (showHud)
const Positioned(top: 8, right: 56, child: _MiniFpsHud()), const Positioned(top: 8, right: 56, child: _MiniFpsHud()),
], ],
),
); );
}, },
theme: baseLightTheme, theme: baseLightTheme,

View File

@@ -24,6 +24,7 @@ import 'package:gwid/screens/edit_contact_screen.dart';
import 'package:gwid/widgets/contact_name_widget.dart'; import 'package:gwid/widgets/contact_name_widget.dart';
import 'package:gwid/widgets/contact_avatar_widget.dart'; import 'package:gwid/widgets/contact_avatar_widget.dart';
import 'package:flutter_linkify/flutter_linkify.dart'; import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'package:video_player/video_player.dart'; import 'package:video_player/video_player.dart';
@@ -343,6 +344,7 @@ class _ChatScreenState extends State<ChatScreen> {
Future<void> _initializeChat() async { Future<void> _initializeChat() async {
await _loadCachedContacts(); await _loadCachedContacts();
final prefs = await SharedPreferences.getInstance();
if (!widget.isGroupChat && !widget.isChannel) { if (!widget.isGroupChat && !widget.isChannel) {
_contactDetailsCache[widget.contact.id] = widget.contact; _contactDetailsCache[widget.contact.id] = widget.contact;
@@ -357,7 +359,8 @@ class _ChatScreenState extends State<ChatScreen> {
if (contactProfile != null && if (contactProfile != null &&
contactProfile['id'] != null && contactProfile['id'] != null &&
contactProfile['id'] != 0) { contactProfile['id'] != 0) {
_actualMyId = contactProfile['id']; String? idStr = await prefs.getString("userId");
_actualMyId = idStr!.isNotEmpty ? int.parse(idStr) : contactProfile['id'];
print( print(
'✅ [_initializeChat] ID пользователя получен из ApiService: $_actualMyId', '✅ [_initializeChat] ID пользователя получен из ApiService: $_actualMyId',
); );
@@ -374,7 +377,8 @@ class _ChatScreenState extends State<ChatScreen> {
); );
} }
} else if (_actualMyId == null) { } else if (_actualMyId == null) {
_actualMyId = widget.myId; final prefs = await SharedPreferences.getInstance();
_actualMyId = int.parse(await prefs.getString('userId')!);;
print( print(
'⚠️ [_initializeChat] ID не найден, используется из виджета: $_actualMyId', '⚠️ [_initializeChat] ID не найден, используется из виджета: $_actualMyId',
); );
@@ -1129,13 +1133,13 @@ class _ChatScreenState extends State<ChatScreen> {
final int tempCid = DateTime.now().millisecondsSinceEpoch; final int tempCid = DateTime.now().millisecondsSinceEpoch;
final tempMessageJson = { final tempMessageJson = {
'id': 'local_$tempCid', // Временный "локальный" ID 'id': 'local_$tempCid',
'text': text, 'text': text,
'time': tempCid, 'time': tempCid,
'sender': _actualMyId!, 'sender': _actualMyId!,
'cid': tempCid, // Уникальный ID клиента 'cid': tempCid,
'type': 'USER', 'type': 'USER',
'attaches': [], // Оптимистично без вложений (для текста) 'attaches': [],
'link': _replyingToMessage != null 'link': _replyingToMessage != null
? { ? {
'type': 'REPLY', 'type': 'REPLY',
@@ -1191,7 +1195,6 @@ class _ChatScreenState extends State<ChatScreen> {
} }
void _testSlideAnimation() { void _testSlideAnimation() {
print('=== ТЕСТ SLIDE+ АНИМАЦИИ ===');
final myMessage = Message( final myMessage = Message(
id: 'test_my_${DateTime.now().millisecondsSinceEpoch}', id: 'test_my_${DateTime.now().millisecondsSinceEpoch}',
@@ -1948,12 +1951,12 @@ class _ChatScreenState extends State<ChatScreen> {
for (final contact in chatContacts) { for (final contact in chatContacts) {
_contactDetailsCache[contact.id] = contact; _contactDetailsCache[contact.id] = contact;
if (contact.id == widget.myId && _actualMyId == null) { /*if (contact.id == widget.myId && _actualMyId == null) {
_actualMyId = contact.id; //_actualMyId = contact.id;
print( print(
'✅ [_loadCachedContacts] Собственный ID восстановлен из кэша: $_actualMyId (${contact.name})', '✅ [_loadCachedContacts] Собственный ID восстановлен из кэша: $_actualMyId (${contact.name})',
); );
} }*/
} }
print( print(
'✅ Загружено ${_contactDetailsCache.length} контактов из кэша чата ${widget.chatId}', '✅ Загружено ${_contactDetailsCache.length} контактов из кэша чата ${widget.chatId}',
@@ -1968,7 +1971,9 @@ class _ChatScreenState extends State<ChatScreen> {
_contactDetailsCache[contact.id] = contact; _contactDetailsCache[contact.id] = contact;
if (contact.id == widget.myId && _actualMyId == null) { if (contact.id == widget.myId && _actualMyId == null) {
_actualMyId = contact.id; final prefs = await SharedPreferences.getInstance();
_actualMyId = int.parse(await prefs.getString('userId')!);
print( print(
'✅ [_loadCachedContacts] Собственный ID восстановлен из глобального кэша: $_actualMyId (${contact.name})', '✅ [_loadCachedContacts] Собственный ID восстановлен из глобального кэша: $_actualMyId (${contact.name})',
); );
@@ -4364,6 +4369,7 @@ extension BrightnessExtension on Brightness {
bool get isDark => this == Brightness.dark; bool get isDark => this == Brightness.dark;
} }
//note: unused
class GroupProfileDraggableDialog extends StatelessWidget { class GroupProfileDraggableDialog extends StatelessWidget {
final Contact contact; final Contact contact;
@@ -4427,8 +4433,6 @@ class GroupProfileDraggableDialog extends StatelessWidget {
IconButton( IconButton(
icon: Icon(Icons.settings, color: colors.primary), icon: Icon(Icons.settings, color: colors.primary),
onPressed: () async { onPressed: () async {
final myId = 0; // This should be passed or retrieved
Navigator.of(context).pop(); Navigator.of(context).pop();
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute( MaterialPageRoute(
@@ -4436,7 +4440,7 @@ class GroupProfileDraggableDialog extends StatelessWidget {
chatId: -contact chatId: -contact
.id, // Convert back to positive chatId .id, // Convert back to positive chatId
initialContact: contact, initialContact: contact,
myId: myId, myId: 0,
), ),
), ),
); );

View File

@@ -259,9 +259,9 @@ class _ChatsScreenState extends State<ChatsScreen>
void _navigateToLogin() { void _navigateToLogin() {
print('Перенаправляем на экран входа из-за недействительного токена'); print('Перенаправляем на экран входа из-за недействительного токена');
Navigator.of(context).pushReplacement( /*Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const PhoneEntryScreen()), MaterialPageRoute(builder: (context) => const PhoneEntryScreen()),
); );*/
} }
void _showTokenExpiredDialog(String message) { void _showTokenExpiredDialog(String message) {

View File

@@ -1242,7 +1242,6 @@ class _DesktopLayoutState extends State<_DesktopLayout> {
isChannel: _isChannel, isChannel: _isChannel,
participantCount: _participantCount, participantCount: _participantCount,
isDesktopMode: true, isDesktopMode: true,
onChatUpdated: () {},
), ),
), ),
], ],

View File

@@ -132,15 +132,21 @@ class _MusicLibraryScreenState extends State<MusicLibraryScreen> {
return ValueListenableBuilder<bool>( return ValueListenableBuilder<bool>(
valueListenable: BottomSheetMusicPlayer.isExpandedNotifier, valueListenable: BottomSheetMusicPlayer.isExpandedNotifier,
builder: (context, isPlayerExpanded, child) { builder: (context, isPlayerExpanded, child) {
return ValueListenableBuilder<bool>(
valueListenable: BottomSheetMusicPlayer.isFullscreenNotifier,
builder: (context, isFullscreen, _) {
return PopScope( return PopScope(
canPop: !isPlayerExpanded, canPop: !isPlayerExpanded,
onPopInvoked: (didPop) { onPopInvoked: (didPop) {
if (!didPop && isPlayerExpanded) { if (!didPop && isPlayerExpanded) {
BottomSheetMusicPlayer.isExpandedNotifier.value = false; BottomSheetMusicPlayer.isExpandedNotifier.value = false;
BottomSheetMusicPlayer.isFullscreenNotifier.value = false;
} }
}, },
child: Scaffold( child: Scaffold(
appBar: AppBar(title: const Text('Музыка')), appBar: isFullscreen
? null
: AppBar(title: const Text('Музыка')),
body: Stack( body: Stack(
children: [ children: [
_isLoading _isLoading
@@ -325,5 +331,7 @@ class _MusicLibraryScreenState extends State<MusicLibraryScreen> {
); );
}, },
); );
},
);
} }
} }

View File

@@ -56,7 +56,7 @@ class _OTPScreenState extends State<OTPScreen> {
if (payload != null && if (payload != null &&
payload['tokenAttrs']?['LOGIN']?['token'] != null) { payload['tokenAttrs']?['LOGIN']?['token'] != null) {
final String finalToken = payload['tokenAttrs']['LOGIN']['token']; final String finalToken = payload['tokenAttrs']['LOGIN']['token'];
final userId = payload['tokenAttrs']?['LOGIN']?['userId']; final userId = payload['payload']?['profile']?['contact']?['id'];
print('Успешная авторизация! Токен: $finalToken, UserID: $userId'); print('Успешная авторизация! Токен: $finalToken, UserID: $userId');
ApiService.instance ApiService.instance

View File

@@ -202,16 +202,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text("Настройки"), title: const Text("Настройки"),
leading: widget.showBackToChats /*leading: widget.showBackToChats
? IconButton( ? IconButton(
icon: const Icon(Icons.arrow_back), icon: const Icon(Icons.arrow_back),
onPressed: widget.onBackToChats, onPressed: widget.onBackToChats,
) )
: null, : null,*/
),
body: SafeArea(
child: _buildSettingsContent(),
), ),
body: _buildSettingsContent(),
); );
} }
@@ -224,8 +222,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
final isSmallScreen = screenWidth < 600 || screenHeight < 800; final isSmallScreen = screenWidth < 600 || screenHeight < 800;
return Scaffold( return Scaffold(
backgroundColor: Colors.transparent, body: SafeArea(
body: Stack( child: Stack(
children: [ children: [
GestureDetector( GestureDetector(
onTap: () => Navigator.of(context).pop(), onTap: () => Navigator.of(context).pop(),
@@ -346,7 +344,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
), ),
), ),
], ],
), )),
); );
} }

View File

@@ -104,6 +104,7 @@ class MusicPlayerService extends ChangeNotifier {
StreamSubscription<Duration>? _positionSubscription; StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<Duration?>? _durationSubscription; StreamSubscription<Duration?>? _durationSubscription;
StreamSubscription<PlayerState>? _playerStateSubscription; StreamSubscription<PlayerState>? _playerStateSubscription;
bool _wasCompleted = false;
MusicTrack? get currentTrack => MusicTrack? get currentTrack =>
_currentIndex >= 0 && _currentIndex < _playlist.length _currentIndex >= 0 && _currentIndex < _playlist.length
@@ -129,10 +130,20 @@ class MusicPlayerService extends ChangeNotifier {
}); });
_playerStateSubscription = _audioPlayer.playerStateStream.listen((state) { _playerStateSubscription = _audioPlayer.playerStateStream.listen((state) {
final wasCompleted = _wasCompleted;
_isPlaying = state.playing; _isPlaying = state.playing;
_isLoading = _isLoading =
state.processingState == ProcessingState.loading || state.processingState == ProcessingState.loading ||
state.processingState == ProcessingState.buffering; state.processingState == ProcessingState.buffering;
// Detect track completion and auto-play next track
if (state.processingState == ProcessingState.completed && !wasCompleted) {
_wasCompleted = true;
_autoPlayNext();
} else if (state.processingState != ProcessingState.completed) {
_wasCompleted = false;
}
notifyListeners(); notifyListeners();
}); });
@@ -257,6 +268,20 @@ class MusicPlayerService extends ChangeNotifier {
await savePlaylist(); await savePlaylist();
} }
Future<void> _autoPlayNext() async {
if (_playlist.isEmpty || _playlist.length <= 1) return;
try {
_currentIndex = (_currentIndex + 1) % _playlist.length;
await _loadAndPlayTrack(_playlist[_currentIndex]);
await savePlaylist();
} catch (e) {
print('Error auto-playing next track: $e');
_isLoading = false;
notifyListeners();
}
}
Future<void> addToPlaylist(MusicTrack track) async { Future<void> addToPlaylist(MusicTrack track) async {
if (!_playlist.any((t) => t.id == track.id)) { if (!_playlist.any((t) => t.id == track.id)) {
_playlist.add(track); _playlist.add(track);

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../services/music_player_service.dart'; import '../services/music_player_service.dart';
@@ -8,36 +9,73 @@ class BottomSheetMusicPlayer extends StatefulWidget {
static final ValueNotifier<bool> isExpandedNotifier = ValueNotifier<bool>( static final ValueNotifier<bool> isExpandedNotifier = ValueNotifier<bool>(
false, false,
); );
static final ValueNotifier<bool> isFullscreenNotifier = ValueNotifier<bool>(
false,
);
@override @override
State<BottomSheetMusicPlayer> createState() => _BottomSheetMusicPlayerState(); State<BottomSheetMusicPlayer> createState() => _BottomSheetMusicPlayerState();
} }
enum _PlayerState { collapsed, expanded, fullscreen }
class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer> class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
late AnimationController _animationController; late AnimationController _animationController;
bool _isExpanded = false; late Animation<double> _heightAnimation;
late Animation<double> _opacityAnimation;
_PlayerState _currentState = _PlayerState.collapsed;
static const Duration _animationDuration = Duration(milliseconds: 300);
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_animationController = AnimationController( _animationController = AnimationController(
vsync: this, vsync: this,
duration: const Duration(milliseconds: 200), duration: _animationDuration,
);
_heightAnimation = CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOutCubic,
);
_opacityAnimation = CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
); );
BottomSheetMusicPlayer.isExpandedNotifier.addListener(_onExpandedChanged); BottomSheetMusicPlayer.isExpandedNotifier.addListener(_onExpandedChanged);
BottomSheetMusicPlayer.isFullscreenNotifier.addListener(_onFullscreenChanged);
} }
void _onExpandedChanged() { void _onExpandedChanged() {
final shouldBeExpanded = BottomSheetMusicPlayer.isExpandedNotifier.value; final shouldBeExpanded = BottomSheetMusicPlayer.isExpandedNotifier.value;
if (shouldBeExpanded != _isExpanded) { if (shouldBeExpanded && _currentState == _PlayerState.collapsed) {
setState(() { setState(() {
_isExpanded = shouldBeExpanded; _currentState = _PlayerState.expanded;
if (_isExpanded) {
_animationController.forward(); _animationController.forward();
} else { });
} else if (!shouldBeExpanded && _currentState != _PlayerState.collapsed) {
setState(() {
_currentState = _PlayerState.collapsed;
_animationController.reverse(); _animationController.reverse();
BottomSheetMusicPlayer.isFullscreenNotifier.value = false;
});
} }
}
void _onFullscreenChanged() {
final shouldBeFullscreen = BottomSheetMusicPlayer.isFullscreenNotifier.value;
if (shouldBeFullscreen && _currentState != _PlayerState.fullscreen) {
setState(() {
_currentState = _PlayerState.fullscreen;
if (_animationController.value < 1.0) {
_animationController.forward();
}
});
} else if (!shouldBeFullscreen &&
_currentState == _PlayerState.fullscreen) {
setState(() {
_currentState = _PlayerState.expanded;
_animationController.value = 1.0;
}); });
} }
} }
@@ -47,18 +85,51 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
BottomSheetMusicPlayer.isExpandedNotifier.removeListener( BottomSheetMusicPlayer.isExpandedNotifier.removeListener(
_onExpandedChanged, _onExpandedChanged,
); );
BottomSheetMusicPlayer.isFullscreenNotifier.removeListener(
_onFullscreenChanged,
);
_animationController.dispose(); _animationController.dispose();
super.dispose(); super.dispose();
} }
void _toggleExpand() { void _toggleExpand() {
HapticFeedback.lightImpact();
setState(() { setState(() {
_isExpanded = !_isExpanded; if (_currentState == _PlayerState.collapsed) {
BottomSheetMusicPlayer.isExpandedNotifier.value = _isExpanded; // Tap on collapsed opens directly to fullscreen
if (_isExpanded) { _currentState = _PlayerState.fullscreen;
_animationController.forward(); _animationController.forward();
} else { BottomSheetMusicPlayer.isExpandedNotifier.value = true;
BottomSheetMusicPlayer.isFullscreenNotifier.value = true;
} else if (_currentState == _PlayerState.fullscreen) {
// From fullscreen, go to collapsed
_currentState = _PlayerState.collapsed;
_animationController.reverse(); _animationController.reverse();
BottomSheetMusicPlayer.isExpandedNotifier.value = false;
BottomSheetMusicPlayer.isFullscreenNotifier.value = false;
} else {
// From expanded, go to collapsed
_currentState = _PlayerState.collapsed;
_animationController.reverse();
BottomSheetMusicPlayer.isExpandedNotifier.value = false;
BottomSheetMusicPlayer.isFullscreenNotifier.value = false;
}
});
}
void _toggleFullscreen() {
HapticFeedback.mediumImpact();
setState(() {
if (_currentState == _PlayerState.fullscreen) {
_currentState = _PlayerState.expanded;
// Keep animation at 1.0 for expanded state
_animationController.value = 1.0;
BottomSheetMusicPlayer.isFullscreenNotifier.value = false;
} else {
// Transitioning from expanded to fullscreen
// Animation is already at 1.0, we'll use AnimatedContainer for smooth transition
_currentState = _PlayerState.fullscreen;
BottomSheetMusicPlayer.isFullscreenNotifier.value = true;
} }
}); });
} }
@@ -87,40 +158,72 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
} }
return AnimatedBuilder( return AnimatedBuilder(
animation: _animationController, animation: _heightAnimation,
builder: (context, child) { builder: (context, child) {
final screenHeight = MediaQuery.of(context).size.height; final screenHeight = MediaQuery.of(context).size.height;
final collapsedHeight = 100.0; final collapsedHeight = 88.0;
final expandedHeight = screenHeight * 0.75; final expandedHeight = screenHeight * 0.85;
final animationValue = Curves.easeInOut.transform( final fullscreenHeight = screenHeight;
_animationController.value,
); double targetHeight;
final currentHeight = if (_currentState == _PlayerState.fullscreen) {
collapsedHeight + targetHeight = fullscreenHeight;
(expandedHeight - collapsedHeight) * animationValue; } else if (_currentState == _PlayerState.expanded) {
targetHeight = expandedHeight;
} else {
targetHeight = collapsedHeight;
}
// Interpolate between collapsed and target height
final currentHeight = collapsedHeight +
(targetHeight - collapsedHeight) * _heightAnimation.value;
return Material( return Material(
color: Colors.transparent, color: Colors.transparent,
elevation: 0,
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: _animationDuration,
curve: Curves.easeInOut, curve: Curves.easeInOutCubic,
height: currentHeight, height: currentHeight,
decoration: BoxDecoration( decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest, color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.only( borderRadius: _currentState == _PlayerState.fullscreen
topLeft: const Radius.circular(24), ? BorderRadius.zero
topRight: const Radius.circular(24), : BorderRadius.only(
bottomLeft: Radius.circular(24 * (1 - animationValue)), topLeft: const Radius.circular(28),
bottomRight: Radius.circular(24 * (1 - animationValue)), topRight: const Radius.circular(28),
bottomLeft: Radius.circular(
28 * (1 - _heightAnimation.value),
), ),
boxShadow: [ bottomRight: Radius.circular(
28 * (1 - _heightAnimation.value),
),
),
boxShadow: _currentState == _PlayerState.fullscreen
? []
: [
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(0.2), color: Colors.black.withOpacity(
blurRadius: 12, 0.15 * _heightAnimation.value,
offset: const Offset(0, -4), ),
blurRadius: 20,
offset: Offset(0, -6 * _heightAnimation.value),
), ),
], ],
), ),
child: ClipRRect(
borderRadius: _currentState == _PlayerState.fullscreen
? BorderRadius.zero
: BorderRadius.only(
topLeft: const Radius.circular(28),
topRight: const Radius.circular(28),
bottomLeft: Radius.circular(
28 * (1 - _heightAnimation.value),
),
bottomRight: Radius.circular(
28 * (1 - _heightAnimation.value),
),
),
child: _buildAnimatedContent( child: _buildAnimatedContent(
context, context,
musicPlayer, musicPlayer,
@@ -128,6 +231,7 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
colorScheme, colorScheme,
), ),
), ),
),
); );
}, },
); );
@@ -140,27 +244,29 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
ColorScheme colorScheme, ColorScheme colorScheme,
) { ) {
return AnimatedSwitcher( return AnimatedSwitcher(
duration: const Duration(milliseconds: 300), duration: _animationDuration,
switchInCurve: Curves.easeInOut, switchInCurve: Curves.easeInOutCubic,
switchOutCurve: Curves.easeInOut, switchOutCurve: Curves.easeInOutCubic,
transitionBuilder: (Widget child, Animation<double> animation) { transitionBuilder: (Widget child, Animation<double> animation) {
return FadeTransition( return FadeTransition(
opacity: animation, opacity: animation,
child: SlideTransition( child: SlideTransition(
position: position: Tween<Offset>(
Tween<Offset>( begin: const Offset(0.0, 0.05),
begin: const Offset(0.0, 0.1),
end: Offset.zero, end: Offset.zero,
).animate( ).animate(
CurvedAnimation(parent: animation, curve: Curves.easeInOut), CurvedAnimation(
parent: animation,
curve: Curves.easeOutCubic,
),
), ),
child: child, child: child,
), ),
); );
}, },
child: _isExpanded child: _currentState == _PlayerState.collapsed
? _buildExpandedView(context, musicPlayer, track, colorScheme) ? _buildCollapsedView(context, musicPlayer, track, colorScheme)
: _buildCollapsedView(context, musicPlayer, track, colorScheme), : _buildExpandedView(context, musicPlayer, track, colorScheme),
); );
} }
@@ -173,29 +279,39 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
return SafeArea( return SafeArea(
key: const ValueKey('collapsed'), key: const ValueKey('collapsed'),
top: false, top: false,
child: GestureDetector( child: Material(
color: Colors.transparent,
child: InkWell(
onTap: _toggleExpand, onTap: _toggleExpand,
borderRadius: BorderRadius.circular(28),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row( child: Row(
children: [ children: [
ClipRRect( Hero(
borderRadius: BorderRadius.circular(8), tag: 'album-art-${track.id}',
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Container( child: Container(
width: 48, width: 64,
height: 48, height: 64,
color: colorScheme.primaryContainer, color: colorScheme.primaryContainer,
child: track.albumArtUrl != null child: track.albumArtUrl != null
? Image.network( ? Image.network(
track.albumArtUrl!, track.albumArtUrl!,
fit: BoxFit.cover, fit: BoxFit.cover,
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
return _buildAlbumArtPlaceholder(colorScheme);
},
errorBuilder: (context, error, stackTrace) => errorBuilder: (context, error, stackTrace) =>
_buildAlbumArtPlaceholder(colorScheme), _buildAlbumArtPlaceholder(colorScheme),
) )
: _buildAlbumArtPlaceholder(colorScheme), : _buildAlbumArtPlaceholder(colorScheme),
), ),
), ),
const SizedBox(width: 10), ),
const SizedBox(width: 16),
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -204,18 +320,19 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
children: [ children: [
Text( Text(
track.title, track.title,
style: Theme.of(context).textTheme.titleSmall?.copyWith( style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
letterSpacing: -0.2,
), ),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
const SizedBox(height: 4), const SizedBox(height: 6),
Text( Text(
track.artist, track.artist,
style: Theme.of(context).textTheme.bodySmall?.copyWith( style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface.withOpacity(0.7), color: colorScheme.onSurface.withOpacity(0.65),
fontSize: 12, fontSize: 13,
), ),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
@@ -223,33 +340,49 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
], ],
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 12),
GestureDetector( Material(
color: Colors.transparent,
child: InkWell(
onTap: () { onTap: () {
HapticFeedback.selectionClick();
if (musicPlayer.isPlaying) { if (musicPlayer.isPlaying) {
musicPlayer.pause(); musicPlayer.pause();
} else { } else {
musicPlayer.resume(); musicPlayer.resume();
} }
}, },
borderRadius: BorderRadius.circular(24),
child: Container( child: Container(
width: 40, width: 48,
height: 40, height: 48,
decoration: BoxDecoration( decoration: BoxDecoration(
color: colorScheme.primary, color: colorScheme.primary,
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Icon( child: musicPlayer.isLoading
? Padding(
padding: const EdgeInsets.all(12),
child: CircularProgressIndicator(
strokeWidth: 2.5,
valueColor: AlwaysStoppedAnimation<Color>(
colorScheme.onPrimary,
),
),
)
: Icon(
musicPlayer.isPlaying ? Icons.pause : Icons.play_arrow, musicPlayer.isPlaying ? Icons.pause : Icons.play_arrow,
size: 24, size: 26,
color: colorScheme.onPrimary, color: colorScheme.onPrimary,
), ),
), ),
), ),
),
], ],
), ),
), ),
), ),
),
); );
} }
@@ -261,68 +394,78 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
) { ) {
return SafeArea( return SafeArea(
key: const ValueKey('expanded'), key: const ValueKey('expanded'),
top: false, top: _currentState == _PlayerState.fullscreen,
child: Column( child: Column(
children: [ children: [
GestureDetector( Row(
children: [
if (_currentState == _PlayerState.fullscreen)
Material(
color: Colors.transparent,
child: InkWell(
onTap: _toggleExpand, onTap: _toggleExpand,
onVerticalDragEnd: (details) { borderRadius: BorderRadius.circular(24),
if (details.primaryVelocity != null &&
details.primaryVelocity! > 200) {
_toggleExpand();
}
},
child: Container( child: Container(
margin: const EdgeInsets.only(top: 12), margin: const EdgeInsets.only(top: 8, right: 16),
padding: const EdgeInsets.symmetric(vertical: 12), padding: const EdgeInsets.all(12),
width: double.infinity, child: Icon(
child: Center( Icons.fullscreen_exit_rounded,
child: Container( color: colorScheme.onSurface,
width: 40, size: 24,
height: 4,
decoration: BoxDecoration(
color: colorScheme.onSurface.withOpacity(0.3),
borderRadius: BorderRadius.circular(2),
), ),
), ),
), ),
), ),
],
), ),
Expanded( Expanded(
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Padding( child: Padding(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
const SizedBox(height: 8),
// Album art with hero animation
LayoutBuilder( LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final maxWidth = constraints.maxWidth; final maxWidth = constraints.maxWidth;
final albumSize = maxWidth < 400 ? maxWidth : 400.0; final albumSize = maxWidth < 380 ? maxWidth : 380.0;
return Container( return Hero(
tag: 'album-art-${track.id}',
child: Container(
width: albumSize, width: albumSize,
height: albumSize, height: albumSize,
margin: EdgeInsets.symmetric( margin: EdgeInsets.symmetric(
horizontal: (maxWidth - albumSize) / 2, horizontal: (maxWidth - albumSize) / 2,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24), borderRadius: BorderRadius.circular(32),
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(0.3), color: Colors.black.withOpacity(0.25),
blurRadius: 20, blurRadius: 30,
offset: const Offset(0, 10), offset: const Offset(0, 12),
spreadRadius: 2,
), ),
], ],
), ),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(24), borderRadius: BorderRadius.circular(32),
child: track.albumArtUrl != null child: track.albumArtUrl != null
? Image.network( ? Image.network(
track.albumArtUrl!, track.albumArtUrl!,
fit: BoxFit.cover, fit: BoxFit.cover,
loadingBuilder:
(context, child, loadingProgress) {
if (loadingProgress == null) {
return child;
}
return _buildLargeAlbumArtPlaceholder(
context,
colorScheme,
);
},
errorBuilder: errorBuilder:
(context, error, stackTrace) => (context, error, stackTrace) =>
_buildLargeAlbumArtPlaceholder( _buildLargeAlbumArtPlaceholder(
@@ -335,74 +478,107 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
colorScheme, colorScheme,
), ),
), ),
),
); );
}, },
), ),
const SizedBox(height: 16), const SizedBox(height: 32),
// Track info
Text( Text(
track.title, track.title,
style: Theme.of(context).textTheme.headlineSmall style: Theme.of(context).textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold), ?.copyWith(
textAlign: TextAlign.center, fontWeight: FontWeight.bold,
letterSpacing: -0.5,
), ),
const SizedBox(height: 8), textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 12),
Text( Text(
track.artist, track.artist,
style: Theme.of(context).textTheme.titleMedium?.copyWith( style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: colorScheme.onSurface.withOpacity(0.7), color: colorScheme.onSurface.withOpacity(0.75),
fontWeight: FontWeight.w500,
), ),
textAlign: TextAlign.center, textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
), ),
if (track.album != null) ...[ if (track.album != null) ...[
const SizedBox(height: 4), const SizedBox(height: 8),
Text( Text(
track.album!, track.album!,
style: Theme.of(context).textTheme.bodyMedium?.copyWith( style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6), color: colorScheme.onSurface.withOpacity(0.6),
), ),
textAlign: TextAlign.center, textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
), ),
], ],
const SizedBox(height: 32), const SizedBox(height: 40),
// Progress slider
Column( Column(
children: [ children: [
Slider( SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: colorScheme.primary,
inactiveTrackColor:
colorScheme.surfaceContainerHigh,
thumbColor: colorScheme.primary,
overlayColor:
colorScheme.primary.withOpacity(0.1),
thumbShape: const RoundSliderThumbShape(
enabledThumbRadius: 8,
),
trackHeight: 4,
),
child: Slider(
value: musicPlayer.duration.inMilliseconds > 0 value: musicPlayer.duration.inMilliseconds > 0
? musicPlayer.position.inMilliseconds / ? (musicPlayer.position.inMilliseconds /
musicPlayer.duration.inMilliseconds musicPlayer.duration.inMilliseconds)
.clamp(0.0, 1.0)
: 0.0, : 0.0,
onChanged: (value) { onChanged: (value) {
HapticFeedback.selectionClick();
final newPosition = Duration( final newPosition = Duration(
milliseconds: milliseconds: (value *
(value * musicPlayer.duration.inMilliseconds) musicPlayer.duration.inMilliseconds)
.round(), .round(),
); );
musicPlayer.seek(newPosition); musicPlayer.seek(newPosition);
}, },
activeColor: colorScheme.primary, ),
inactiveColor: colorScheme.surfaceContainerHigh,
), ),
Padding( Padding(
padding: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text( Text(
_formatDuration(musicPlayer.position), _formatDuration(musicPlayer.position),
style: Theme.of(context).textTheme.bodySmall style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith( ?.copyWith(
color: colorScheme.onSurface.withOpacity( color: colorScheme.onSurface
0.7, .withOpacity(0.7),
), fontWeight: FontWeight.w500,
fontSize: 13,
), ),
), ),
Text( Text(
_formatDuration(musicPlayer.duration), _formatDuration(musicPlayer.duration),
style: Theme.of(context).textTheme.bodySmall style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith( ?.copyWith(
color: colorScheme.onSurface.withOpacity( color: colorScheme.onSurface
0.7, .withOpacity(0.7),
), fontWeight: FontWeight.w500,
fontSize: 13,
), ),
), ),
], ],
@@ -410,72 +586,108 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
), ),
], ],
), ),
const SizedBox(height: 24), const SizedBox(height: 16),
// Control buttons
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
IconButton( Material(
onPressed: musicPlayer.previous, color: Colors.transparent,
icon: const Icon(Icons.skip_previous), child: InkWell(
iconSize: 32, onTap: () {
style: IconButton.styleFrom( HapticFeedback.selectionClick();
backgroundColor: colorScheme.surfaceContainerHigh, musicPlayer.previous();
foregroundColor: colorScheme.onSurface, },
padding: const EdgeInsets.all(16), borderRadius: BorderRadius.circular(28),
child: Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
shape: BoxShape.circle,
),
child: Icon(
Icons.skip_previous_rounded,
size: 28,
color: colorScheme.onSurface,
), ),
), ),
const SizedBox(width: 16), ),
FilledButton( ),
onPressed: () { const SizedBox(width: 24),
Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
HapticFeedback.mediumImpact();
if (musicPlayer.isPlaying) { if (musicPlayer.isPlaying) {
musicPlayer.pause(); musicPlayer.pause();
} else { } else {
musicPlayer.resume(); musicPlayer.resume();
} }
}, },
style: FilledButton.styleFrom( borderRadius: BorderRadius.circular(40),
backgroundColor: colorScheme.primary, child: Container(
foregroundColor: colorScheme.onPrimary, width: 80,
padding: const EdgeInsets.all(20), height: 80,
shape: const CircleBorder(), decoration: BoxDecoration(
minimumSize: const Size(72, 72), color: colorScheme.primary,
shape: BoxShape.circle,
), ),
child: musicPlayer.isLoading child: musicPlayer.isLoading
? SizedBox( ? Padding(
width: 32, padding: const EdgeInsets.all(24),
height: 32,
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 3, strokeWidth: 3,
valueColor: AlwaysStoppedAnimation<Color>( valueColor:
AlwaysStoppedAnimation<Color>(
colorScheme.onPrimary, colorScheme.onPrimary,
), ),
), ),
) )
: Icon( : Icon(
musicPlayer.isPlaying musicPlayer.isPlaying
? Icons.pause ? Icons.pause_rounded
: Icons.play_arrow, : Icons.play_arrow_rounded,
size: 36, size: 40,
color: colorScheme.onPrimary,
),
),
),
),
const SizedBox(width: 24),
Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
HapticFeedback.selectionClick();
musicPlayer.next();
},
borderRadius: BorderRadius.circular(28),
child: Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
shape: BoxShape.circle,
),
child: Icon(
Icons.skip_next_rounded,
size: 28,
color: colorScheme.onSurface,
), ),
), ),
const SizedBox(width: 16),
IconButton(
onPressed: musicPlayer.next,
icon: const Icon(Icons.skip_next),
iconSize: 32,
style: IconButton.styleFrom(
backgroundColor: colorScheme.surfaceContainerHigh,
foregroundColor: colorScheme.onSurface,
padding: const EdgeInsets.all(16),
), ),
), ),
], ],
), ),
const SizedBox(height: 24), SizedBox(
height: MediaQuery.of(context).padding.bottom + 24,
),
], ],
), ),
), ),
),
), ),
], ],
), ),
@@ -484,11 +696,22 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
Widget _buildAlbumArtPlaceholder(ColorScheme colorScheme) { Widget _buildAlbumArtPlaceholder(ColorScheme colorScheme) {
return Container( return Container(
color: colorScheme.primaryContainer, decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
colorScheme.primaryContainer,
colorScheme.primaryContainer.withOpacity(0.7),
],
),
),
child: Center(
child: Icon( child: Icon(
Icons.music_note, Icons.music_note_rounded,
color: colorScheme.onPrimaryContainer, color: colorScheme.onPrimaryContainer.withOpacity(0.7),
size: 28, size: 32,
),
), ),
); );
} }
@@ -500,11 +723,22 @@ class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
return Container( return Container(
width: double.infinity, width: double.infinity,
height: double.infinity, height: double.infinity,
color: colorScheme.primaryContainer, decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
colorScheme.primaryContainer,
colorScheme.primaryContainer.withOpacity(0.6),
],
),
),
child: Center(
child: Icon( child: Icon(
Icons.music_note, Icons.music_note_rounded,
color: colorScheme.onPrimaryContainer, color: colorScheme.onPrimaryContainer.withOpacity(0.6),
size: 80, size: 100,
),
), ),
); );
} }