I'm facing an issue with updating icons in my Flutter mini player widget. The widget displays an image, song name, and an IconButton for pausing and playing the audio. The problem is that when I tap the IconButton, the song pauses and plays correctly, but the icon doesn't update.
I have a miniPlayer method that builds the mini player widget. Inside the method, I'm using an isPlaying variable to track the playing state and toggle the icon accordingly. However, the icon doesn't change when the playing state changes.
I've tried using setState(() {}) to trigger a rebuild and update the icon, but it caused the song to stop playing. When I removed setState(() {}), the song played and paused correctly, but the icon didn't change.
I'm using the AudioPlayer package for audio playback. The relevant code snippet for the mini player is as follows:
Widget miniPlayer(Music? music, {bool stop = false}) {
this.music = music;
if (music == null) {
return SizedBox();
}
if (stop) {
isPlaying = false;
_audioPlayer.stop();
}
//setState(() {});
// Automatically play the song when mini player is shown
if (!isPlaying && !stop) {
isPlaying = true;
_audioPlayer.play(UrlSource(music.audioURL));
}
setState(() {});
Size deviceSize =
MediaQuery.of(context).size; //<-- This is use for responsive
//Mini player code:-
return AnimatedContainer(
duration: const Duration(milliseconds: 500),
color: Colors.blueGrey,
width: deviceSize.width,
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.network(
music.image,
fit: BoxFit.cover,
),
Text(
music.name,
style: const TextStyle(color: Colors.white),
),
IconButton(
onPressed: () async {
isPlaying = !isPlaying;
if (isPlaying) {
// _audioPlayer.play(music.audioURL as Source);
await _audioPlayer.play(UrlSource(music.audioURL));
} else {
await _audioPlayer.pause();
}
//setState(() {});
},
icon: isPlaying
? const Icon(
Icons.pause,
color: Colors.white,
)
: const Icon(
Icons.play_arrow,
color: Colors.white,
),
),
],
),
);
}
I've also tried using a custom PlayPauseButton widget with a GestureDetector and an Icon widget, but encountered the same issue with the icon not updating.
Could you please provide guidance on how to correctly update the icon in the mini player widget when the playing state changes? Any help would be greatly appreciated.
Thank you in advance for your assistance!