Home > Enterprise >  Provider to Riverpod
Provider to Riverpod

Time:10-01

So I am using the Flutter game template, which I found 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(),
          ),

But unfortunately, I don't like provider. How to convert this provider to riverpod?

CodePudding user response:

An equivalent in Riverpod would be:

final settingsProvider = Provider<SettingsController>(...);
final appLifecycleStateProvider = Provider<ValueNotifier<AppLifecycleState>>(...);


final audioControllerProivder = Provider<AudioController>((ref) {
  final audio = AudioController()..initialize();
  ref.onDispose(audio.dispose);

  ref.listen<SettingsController>(settingsProvider, (prev, next) {
    audio.attachSettings(next);
  });
  ref.listen<ValueNotifier<AppLifecycleState>>(appLifecycleStateProvider, (prev, next) {
    audio.attachLifecycleNotifier(next);
  });

  return audio;
});

Although it's possible that there are ways to simplify this further by using ref.watch. But the snippet above should be a good start

  • Related