I got some situations where I needed to use a provider to get some values in scopes where I did not had the context
variable available. For example on a initState
.
One thing that worked was to create the provider as a Singleton and then use it, like this:
locator.registerLazySingleton(() => GameProvider());
final GameProvider _gameProvider = GetIt.instance<GameProvider>();
runApp(ChangeNotifierProvider(
child: MultiProvider(
providers: [
ChangeNotifierProvider<GameProvider>(create: (ctx) => _gameProvider),
], child: MyApp())));
Notice how I am first adding the provider class as a singleton, then getting its value and using ad the instance of the provider itself.
This allows me to use that as a regular provider but to also do something like this:
@override
void initState() {
super.initState();
final GameProvider _gameProvider = GetIt.instance<GameProvider>();
How bad practice is this? It seems there I am getting the best of both worlds being able to have the notifications of a provider and to use it whenever I want for a state management solution.
Is creating several Proxies a better way? Thoughts?