1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-08 13:58:47 +00:00
Files
samples/provider_shopper/lib/models/cart.dart
Filip Hracek c121b2d2a6 Follow best practice of ProxyProvider updating (#298)
* Upgrade to pkg:provider 4.0

* Follow best practice of ProxyProvider updating

The addresses feedback from https://github.com/flutter/samples/issues/245. Instead of constructing a new `CartModel`, we merely update the `catalog` field.

We no longer need a fancy constructor, and `CartModel._catalog` cannot be final any more.
2020-01-31 13:25:14 -08:00

44 lines
1.5 KiB
Dart

// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:provider_shopper/models/catalog.dart';
class CartModel extends ChangeNotifier {
/// The private field backing [catalog].
CatalogModel _catalog;
/// Internal, private state of the cart. Stores the ids of each item.
final List<int> _itemIds = [];
/// The current catalog. Used to construct items from numeric ids.
CatalogModel get catalog => _catalog;
set catalog(CatalogModel newCatalog) {
assert(newCatalog != null);
assert(_itemIds.every((id) => newCatalog.getById(id) != null),
'The catalog $newCatalog does not have one of $_itemIds in it.');
_catalog = newCatalog;
// Notify listeners, in case the new catalog provides information
// different from the previous one. For example, availability of an item
// might have changed.
notifyListeners();
}
/// List of items in the cart.
List<Item> get items => _itemIds.map((id) => _catalog.getById(id)).toList();
/// The current total price of all items.
int get totalPrice =>
items.fold(0, (total, current) => total + current.price);
/// Adds [item] to cart. This is the only way to modify the cart from outside.
void add(Item item) {
_itemIds.add(item.id);
// This line tells [Model] that it should rebuild the widgets that
// depend on it.
notifyListeners();
}
}