skip to Main Content

So, I am fairly new to Riverpod and I use Riverpod mainly because of less page rebuild but when should I use ConsumerWidget as I saw when I use ConsumerWidget it rebuilds the whole widget tree but when using only consumer on that button that it only rebuilds the button’s state not whole page.
so, when should I use ConsumerWidget and Consumer?

2

Answers


  1. Usually ConsumerWidget is used for pages/UI components.
    For example:

    class SomePage extends ConsumerWidget{
    
      @override
      Widget build(BuildContext context, WidgetRef ref){
         SomeValue value = ref.watch(someProvider);
    
         return SomeWidget(value);
    }
    

    On the other hand Consumer is used to watch the provider values locally.
    For example:

    class SomeOtherPage extends StatelessWidget{
    
      @override
      Widget build(BuildContext context){
        return Column(
          children:[
          Text('Consumer'),
          Consumer(
             builder: (context, ref, child) {
              final value = ref.watch(someOtherProvider);
              return Text(value); 
            },
          ),
        ],
       );
      }
    

    It’s recommended to use Consumer when you need to update a little chunk of your widget tree where re-rendering the whole tree is costly.

    Login or Signup to reply.
  2. It’s a matter of choice. You could use Consumer everywhere, or ConsumerWidget instead.

    The recommendation is to generally use ConsumerWidget, for the fact that:

    • They can have a const constructor, so enable more performance optimizations than Consumers.
    • They promote splitting large components into smaller chunks

    For example you could do:

    class SomeOtherPage extends ConsumerWidget {
      const SomeOtherPage({required this.label, super.key});
      final String label;
      @override
      Widget build(BuildContext context, WidgetRef ref){
        return Column(
          children:[
          Text(label),
          const MyText();
        ],
       );
      }
    }
    
    class MyTest extends ConsumerWidget {
      const MyTest({super.key});
      @override
      Widget build(BuildContext context, WidgetRef ref){
        final value = ref.watch(myProvider);
        return Text(value);
      }
    }
    

    In that scenario, if SomeOtherPage.label changes, MyTest will correctly not rebuild and instead only rebuild if myProvider changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search