I am using the game template of Flutter casual game.
Flutter casual game template: Link
They are using a provider actually. They have this:
ProxyProvider2<SettingsController, ValueNotifier<AppLifecycleState>,
AudioController>(
// Ensures that the AudioController is created on startup,
// and not "only when it's needed", as is default behavior.
// This way, music starts immediately.
lazy: false,
create: (context) => AudioController()..initialize(),
update: (context, settings, lifecycleNotifier, audio) {
if (audio == null) throw ArgumentError.notNull();
audio.attachSettings(settings);
audio.attachLifecycleNotifier(lifecycleNotifier);
return audio;
},
dispose: (context, audio) => audio.dispose(),
),
As you can see in the comment of code, it says
`Ensures that the AudioController is Created on startup',
and the ProxyProvider has the dispose parameter and it already pass the audio.dispose()
Therefore, I actually convert this into riverpod:
/// The AudioControllerProvider is used to control the audio of the game.
final audioControllerProvider = Provider.autoDispose<AudioController>((ref) {
// final appLifeCycle = ref.watch(appLifeCycleStateProvider);
final audioController = AudioController();
audioController.initialize();
final settingsController = ref.watch(settingsControllerProvider);
final appLifeCycle = ref.watch(appLifecycleStateProvider);
audioController.attachSettings(settingsController);
audioController.attachLifecycleNotifier(appLifeCycle);
ref.onDispose(audioController.dispose);
return audioController;
});
If we are trying to observe, as you what can see, the provider is auto dispose, and I called the
ref.onDispose()
since the old one has the dispose parameter.
Then since this audio controller must be created on start up. This is what I did, by creating a ProviderContainer before the runApp() function
// Run Some Riverpod Providers during startup
final container = ProviderContainer();
container.read(audioControllerProvider);
runApp(
UncontrolledProviderScope(
container: container,
child: MyApp(
adsController: adsController,
gamesServicesController: gamesServicesController,
),
),
);
So what actually the problems there? It actually working fine at all, the problem there is the dispose. As you can see the audiocontroller was called on startup. But when I go to the new screen by calling this function
GoRouter.of(context).push(
'/game/${questGame[index].gameCategory.gameCategoryKey}');
}),
Then the audio controller it will triggered the dispose. I think the audio controller auto dispose must be not triggered since the provider was called in the main method, right?