I'm currently working on a Flutter application using the just_audio and flutter_riverpod packages. In my project, I've encountered an issue where I get an error message saying "Error: Bad state: Cannot add new events after calling close" originating from the just_audio package.
This error arises when I click on the alarm sound button.
The error occurs within the following function:
Future<void> playSound() async {
if (!_isDisposed) {
final selectedSound = ref.watch(selectedSoundProvider.notifier).state;
await _audioPlayer.setAsset(selectedSound.path); // Error here
_audioPlayer.play();
}
}
I've tried to debug the issue, but I'm having difficulty understanding the source of the problem. I suspect that it might have something to do with the lifecycle of the stream in the just_audio package.
Here are the relevant parts of my code:
timer_notifier.dart:
class TimerNotifier extends StateNotifier<int> {
...
Future<void> playSound() async {
if (!_isDisposed) {
final selectedSound = ref.watch(selectedSoundProvider.notifier).state;
await _audioPlayer.setAsset(selectedSound.path); // Error here
_audioPlayer.play();
}
}
@override
void dispose() {
print('dispose is being called');
_mounted = false;
_timer?.cancel();
_isDisposed = true;
_audioPlayer.dispose();
super.dispose();
}
...
}
settings_page.dart:
class SettingsPage extends ConsumerWidget {
...
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
...
ListTile(
title: Text('Alarm Sound'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: ref.watch(soundListProvider).map((sound) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: ElevatedButton(
onPressed: () async {
ref.read(selectedSoundProvider.notifier).state = sound;
await ref.read(timerNotifierProvider.notifier).playSound();
},
child: Text(sound.friendlyName),
),
);
}).toList(),
),
),
...
}
Could anyone help me understand the issue and guide me step-by-step on where to make the necessary changes to resolve this problem? Any help would be much appreciated.
Thank you!