Creating a shopping cart application with Provider
Create a new Flutter application named cart_provider
and copy item.dart
into your lib
folder, as we have been doing in the previous sections. Also, add dependencies for Provider from pub.dev. Let's get started, as follows:
- Create a new file named
cart_model.dart
and add the following code to it:import 'item.dart'; import 'package:flutter/material.dart'; class Cart with ChangeNotifier { List<Item> _items = populateItems(); List<Item> _cart = []; List<Item> get items => _items; List<Item> get cart => _cart; void addToCart(Item item) { _cart.add(item); notifyListeners(); } void removeFromCart(Item item) { _cart.remove(item); notifyListeners(); } }
As we studied in Chapter 3, Diving into...