1

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?

Leonardo de Jesus
  • 387
  • 1
  • 3
  • 15
  • I don't understand. How can you have the context in an initState, unless it's some stale context from a previous call or parent call? build() hasn't been called yet, and your context *must* come from there. – Randal Schwartz Jan 06 '21 at 00:26
  • I think one of them for specific object is enough. Maybe you can choose one of them to use? [Provider vs. Get_it](https://stackoverflow.com/questions/57169616/provider-vs-get-it) – yellowgray Jan 06 '21 at 07:14

0 Answers0