Search code examples
flutterdartdryriverpodstate-management

How to rebuild StateProvider in RiverPod Flutter


recently I was reading about Riverpod State management in Flutter, and I started using it in my App, I wanted to give a random List of image paths when I press refresh button on my Ui,I made a StateProvider to get the List of random paths from Unsplash url, here is my code

final imgsPathsProvider = StateProvider<List<String>>((ref) {
  return List.generate(
      10,
      (index) =>
          'https://source.unsplash.com/random/?night&${Random().nextInt(1000)}');
});

now I used this provider in my UI when I'm pressing on refresh button, here is my code and it worked well:

 TextButton(
      onPressed: () {
        ref.read(imgsPathsProvider.notifier).update((state) {
          return List.generate(
              10,
              (index) =>
                 'https://source.unsplash.com/random/?night&${Random().nextInt(1000)}');
        });
      },
      child: const Text('refresh'))

the thing is when I press refresh button I want to rebuild the provider to get a random List of images, instead of repeating the code, I feel like I broke DRY principle, this is very simple use case so I used StateProvider instead of NotifierProvider, should I use NotifierProvider instead, and define a method and call it in the UI when pressing refresh? or is there any method to rebuild the state of my StateProvider?


Solution

  • If you simply want to recompute a provider, there is an invalidate method available for WidgetRef.

    onPressed: () {
      ref.invalidate(imgsPathsProvider);
    },
    

    Note that invalidate also works on family provider with or without family parameters, meaning that you could invalidate all family provider or a specific family provider.

    And yes, it is recommended to use NotifierProvider instead of StateProvider mainly for the below reasons.

    1. The logic to update the StateProvider is place inside the widget and it is not reusable and hard to maintain. Using NotifierProvider can centralise the logic.
    2. Riverpod Code generation does not support StateProvider.