Search code examples
riverpodflutter-riverpod

Riverpod 2.0: override with value does not exist anymore


I have a provider named gameControllerProvider extends with ChangeNotifier, I initialize it first throw UnimplementedError.

final gameControllerProvider =
ChangeNotifierProvider<GameController>((ref) => throw UnimplementedError());

In my GameBodyWidget I ovverridewith value my gameControlllerProvider

class GameBodyWidget extends ConsumerWidget {
  /// {@macro game_body_screen}
  const GameBodyWidget({Key? key, required this.gameLevel}) : super(key: key);

  final GameLevel gameLevel;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ProviderScope(
      overrides: [
        gameControllerProvider.overrideWithValue(
          GameController()..initializeController(gameLevel, ref),
        ),
      ],
      child: Stack(
        ...
      ),
    );
  }

As you can see, the reason why I override the controller provider because I need to initialize and pass the parameter of WidgetRef and the GameLevel instance. Yeah I know I can use the .family method but the problem there is that when I need to call this provider I always pass the parameter

ref.watch(gameControllerProvider('exampleParameter'));

Solution

  • I belive this is current correct way:

     runApp( ProviderScope(
          overrides: [
            loggerProvider.overrideWith(
                (StateNotifierProviderRef<Logger, LoggerState> stNP) {return logger;}
            ),
          ],
          child:const MyApp()
      ));