text
stringlengths
1
372
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.