Reputation: 31
I have an app on Flutter with different tabs and on each tab basically I have a different audioplayer. By the way I use the "audioplayers.dart" package.
When the user changes tab, I want the audioplayer to stop. So I put a stop() function in the dispose method.
However, sometimes this isn't working because of states issues.
I wonder if there is an easiest way by forbidding maybe an audioplayer to be play when the user is on another page ?
late AudioPlayer audioplayer;
@override
void initState() {
super.initState();
audioplayer = AudioPlayer(playerId: 'liked_musics');
audioplayer.onDurationChanged.listen((Duration d) {
setState(() => duree = d);
});
audioplayer.onAudioPositionChanged.listen((Duration d) {
setState(() => position = d);
});
audioplayer.onPlayerCompletion.listen((event) {
setState(() {
position = duree;
statut = PlayerState.STOPPED;
});
});
}
@override
dispose() {
audioplayer.stop();
}
Thank you for your help
Joffrey
Upvotes: 0
Views: 1374
Reputation: 723
You can use event bus package
Sample pseudo code:
class AudioStopEvent {
int clickedTabPosition;
AudioStopEvent(this.clickedTabPosition);
}
class BusHelper {
static EventBus eventBus = new EventBus();
}
class YourTabPage{
@override
void initState() {
super.initState();
BusHelper.eventBus.on<AudioStopEvent>().listen((event) {
if(event.clickedTabPosition != currentPagePosition)
audio.stop();
});
}
}
class YourTabManagementClass{
whenChangeTabPage(){
BusHelper.eventBus.fire(new AudioStopEvent(clickedPagePosition)); }
}
Upvotes: 1