Search code examples
flutterriverpod

Multiple simple NotifierProviders better than one "bigger" NotifierProvider with a class as state?


I have a class AppState with a few properties, p1, p2, ...,pn. I now implemented a NotifierProvider for that class.

Would it be better, to create a few extra NotifierProviders for each property, so that a change (e.g. only p1) in the big AppState-NotifierProvider would not cause updates of many widgets, that relay on state, that hasn´t changed in Appstate (e.g. Widget W1 only uses p2 from the AppState). Would W1 update in the case only p1 is updated in AppState?


Solution

  • If your only reason for creating multiple providers is reducing widget rebuilds, that's unnecessary.

    Riverpod has a built-in way to optimize rebuilds in such cases: select

    
    class ConsumerExample extends ConsumerWidget {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        // Instead of writing:
        // String name = ref.watch(provider).firstName!;
        // We can write:
        String name = ref.watch(exampleProvider.select((it) => it.firstName));
        // This will cause the widget to only listen to changes on "firstName".
    
        return Text('Hello $name');
      }
    }
    

    https://riverpod.dev/docs/advanced/select