Updated 28 April 2023
We are going to learn about Consumer and Selector in Flutter.
These terms come in the Flutter provider concept.
It is the most important topic if you care which widget will rebuild when anything updates on the widget.
You can visit Flutter App Development Services from mobikul.
Let’s start with Consumer and selector what is it and why we use it? in Flutter provider.
The provider is using state management in Flutter, Consumer is playing a specific role. Whenever any value update in ChangeNotifier class or we can whenever notifyListeners() is called in ChangeNotifier class then we get the updated value from Consumer block on UI screen. We can call it a listener which listens to updated values
So we can update the UI based on latest data which changed/updated recently.
Lets see the code example –
1 2 3 4 5 |
return Consumer<CartModel>( builder: (context, cart, child) { return Text("Total price: ${cart.totalPrice}"); }, ); |
Whenever CartModel update any value and call notifyListeners then the above block will be executed with cart model instance.
Consumer is Good in state management. Okay then why we use Selector ?
Wait !…….. The consumer has a drawback when you use multiple time consumers at a different-different place for different-different values, for example, the cart model has a total price, product qty, and the seller name.
When you update any of three value in the cart model then all three consumer block will be called and corresponding widget will rebuild.
Suppose you update product quantity then product quantity, total price, and seller name widget will rebuild again. Here, Only product quantity and total price should be rebuilt but the seller name also rebuilds.
To avoid this drawback selector will use in the Flutter provider. It’s working the same as a consumer expect one thing let us see by the code example.
1 2 3 4 5 6 |
return Selector<CartModel,String>( builder: (context, cart, child) { return Text("Total price: ${cart.sellerName}"); },selector: (buildContext , sellerName)=>countPro.getSellerName ); |
Yes, It will call only when seller name will update because we listens only seller name changes.
Thanks for reading.
Reference – https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple
Checkout our blogs – https://mobikul.com/category/flutter/
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.