switchPlayer method
Switch to a different player
Implementation
Future<void> switchPlayer(String playerName) async {
if (!_state.availablePlayers.contains(playerName)) {
_updateState(
_state.copyWith(errorMessage: 'Player $playerName is not available'),
);
return;
}
// Clear current media and set loading state immediately
_updateState(
_state.copyWith(
selectedPlayer: playerName,
isLoading: true,
currentMedia: MediaInfo.empty(), // Clear stale data immediately
),
);
// Stop current listener and all timers
stopListening();
_stopVolumeSync();
_stopMetadataRefresh();
// Small delay to ensure clean state
await Future.delayed(const Duration(milliseconds: 50));
// Fetch current metadata immediately for the new player
try {
final metadata = await _service.getCurrentMetadata(playerName);
if (metadata.isNotEmpty) {
// Force update media directly, bypassing the player check
final media = MediaInfo(
title: metadata['title'] ?? 'Unknown',
artist: metadata['artist'] ?? 'Unknown',
album: metadata['album'] ?? 'Unknown',
status: metadata['status'] ?? 'Stopped',
playerName: metadata['playerName'] ?? 'Unknown',
position: int.tryParse(metadata['position'] ?? '0'),
length: int.tryParse(metadata['length'] ?? '0'),
artUrl: metadata['artUrl']?.isNotEmpty == true
? metadata['artUrl']
: null,
);
_updateState(_state.copyWith(currentMedia: media, errorMessage: ''));
debugPrint('✅ Fetched initial metadata for $playerName');
}
} catch (e) {
debugPrint('Error fetching metadata for player $playerName: $e');
}
// Fetch current volume, shuffle, and loop status for the new player
await updateCurrentVolume();
await updateShuffleStatus();
await updateLoopStatus();
// Start listening to the new player
startListening(playerName);
// Restart volume sync and metadata refresh for the new player
_startVolumeSync();
_startMetadataRefresh();
_updateState(_state.copyWith(isLoading: false));
}