Davoud
Davoud

Reputation: 2933

Problem updating UI with RiverPod in Flutter?

I have a Widget containing a button which increases product quantity in a product list and shows the updated value in a textBox. I am using Riverpod for Statemanagement.

Here is a ItemCounter Widget:

final appNotifier = ref.watch(applicationProvider.notifier);

ItemCounter(
            quantity: appNotifier.getQuantityByProductId(product.id!),
            onChanged: (i) => appNotifier.setProductQuantity(
                i: i, productId: product.id!),
          ), 

When I use above code the UI doesn't update after each click on the button! But when I add this line it works, even though I don't use appProvider anywhere in the code!

// appProvider has no usage in the code but it helps to update UI
final appProvider = ref.watch(applicationProvider);                 <-----This line 
final appNotifier = ref.watch(applicationProvider.notifier);

ItemCounter(
            quantity: appNotifier.getQuantityByProductId(product.id!),
            onChanged: (i) => appNotifier.setProductQuantity(
                i: i, productId: product.id!),
          ), 

Upvotes: 1

Views: 443

Answers (1)

Ruble
Ruble

Reputation: 4824

By design :)

-> When we use ref.watch(applicationProvider), we listen for state changes (and access it) and trigger a rebuild of the widget whenever it has changed.

-> When we use ref.watch(applicationProvider.notifier), we access the listener class and always have the current version of notifier. The rebuilding will not be triggered.

Upvotes: 5

Related Questions