text stringlengths 1 474 |
|---|
state. For very simple apps, you get by with a single ChangeNotifier. |
In complex ones, you’ll have several models, and therefore several |
ChangeNotifiers. (You don’t need to use ChangeNotifier with provider |
at all, but it’s an easy class to work with.)In our shopping app example, we want to manage the state of the cart in a |
ChangeNotifier. We create a new class that extends it, like so: |
<code_start>class CartModel extends ChangeNotifier { |
/// Internal, private state of the cart. |
final List<Item> _items = []; |
/// An unmodifiable view of the items in the cart. |
UnmodifiableListView<Item> get items => UnmodifiableListView(_items); |
/// The current total price of all items (assuming all items cost $42). |
int get totalPrice => _items.length * 42; |
/// Adds [item] to cart. This and [removeAll] are the only ways to modify the |
/// cart from the outside. |
void add(Item item) { |
_items.add(item); |
// This call tells the widgets that are listening to this model to rebuild. |
notifyListeners(); |
} |
/// Removes all items from the cart. |
void removeAll() { |
_items.clear(); |
// This call tells the widgets that are listening to this model to rebuild. |
notifyListeners(); |
} |
}<code_end> |
The only code that is specific to ChangeNotifier is the call |
to notifyListeners(). Call this method any time the model changes in a way |
that might change your app’s UI. Everything else in CartModel is the |
model itself and its business logic.ChangeNotifier is part of flutter:foundation and doesn’t depend on |
any higher-level classes in Flutter. It’s easily testable (you don’t even need |
to use widget testing for it). For example, |
here’s a simple unit test of CartModel: |
<code_start>test('adding item increases total cost', () { |
final cart = CartModel(); |
final startingPrice = cart.totalPrice; |
var i = 0; |
cart.addListener(() { |
expect(cart.totalPrice, greaterThan(startingPrice)); |
i++; |
}); |
cart.add(Item('Dash')); |
expect(i, 1); |
});<code_end> |
<topic_end> |
<topic_start> |
ChangeNotifierProvider |
ChangeNotifierProvider is the widget that provides an instance of |
a ChangeNotifier to its descendants. It comes from the provider package.We already know where to put ChangeNotifierProvider: above the widgets that |
need to access it. In the case of CartModel, that means somewhere |
above both MyCart and MyCatalog.You don’t want to place ChangeNotifierProvider higher than necessary |
(because you don’t want to pollute the scope). But in our case, |
the only widget that is on top of both MyCart and MyCatalog is MyApp. |
<code_start>void main() { |
runApp( |
ChangeNotifierProvider( |
create: (context) => CartModel(), |
child: const MyApp(), |
), |
); |
}<code_end> |
Note that we’re defining a builder that creates a new instance |
of CartModel. ChangeNotifierProvider is smart enough not to rebuild |
CartModel unless absolutely necessary. It also automatically calls |
dispose() on CartModel when the instance is no longer needed.If you want to provide more than one class, you can use MultiProvider: |
<code_start>void main() { |
runApp( |
MultiProvider( |
providers: [ |
ChangeNotifierProvider(create: (context) => CartModel()), |
Provider(create: (context) => SomeOtherClass()), |
], |
child: const MyApp(), |
), |
); |
}<code_end> |
<topic_end> |
<topic_start> |
Consumer |
Now that CartModel is provided to widgets in our app through the |
ChangeNotifierProvider declaration at the top, we can start using it.This is done through the Consumer widget. |
<code_start>return Consumer<CartModel>( |
builder: (context, cart, child) { |
return Text('Total price: ${cart.totalPrice}'); |
}, |
);<code_end> |
We must specify the type of the model that we want to access. |
In this case, we want CartModel, so we write |
Consumer<CartModel>. If you don’t specify the generic (<CartModel>), |
the provider package won’t be able to help you. provider is based on types, |
and without the type, it doesn’t know what you want.The only required argument of the Consumer widget |
is the builder. Builder is a function that is called whenever the |
ChangeNotifier changes. (In other words, when you call notifyListeners() |
in your model, all the builder methods of all the corresponding |
Consumer widgets are called.)The builder is called with three arguments. The first one is context, |
which you also get in every build method.The second argument of the builder function is the instance of |
the ChangeNotifier. It’s what we were asking for in the first place. |
You can use the data in the model to define what the UI should look like |
at any given point.The third argument is child, which is there for optimization. |
If you have a large widget subtree under your Consumer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.