Advertisement
ak133720

flutter scoped model

Nov 18th, 2021
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. // scoped-models/products.dart
  2. import 'package:scoped_model/scoped_model.dart';
  3.  
  4. import '../models/product.dart';
  5.  
  6. class ProductsModel extends Model {
  7. List<Product> _products = [];
  8. int? _selectedProductIndex; // if we changed from var => int ?
  9. bool _showFavorites = false;
  10.  
  11. List<Product> get products {
  12. return List.from(_products);
  13. }
  14.  
  15. List<Product> get displayedProducts {
  16. if (_showFavorites) {
  17. return _products.where((Product product) => product.isFavourite).toList();
  18. }
  19. return List.from(_products);
  20. }
  21.  
  22. int get selectedProductIndex{
  23. return _selectedProductIndex!.toInt();
  24. }
  25.  
  26. Product get selectedProduct {
  27. // Error gone here :)
  28. // But need to dive ..
  29. //return _selectedProductIndex;
  30. //If i uncomment underline :: Error happened
  31. return _products[_selectedProductIndex!.toInt()];
  32. }
  33.  
  34. bool get displayFavoritesOnly {
  35. return _showFavorites;
  36. }
  37.  
  38. void addProduct(Product product) {
  39. _products.add(product);
  40. //Chnaged to null frrom 0
  41. // _selectedProductIndex = null;
  42. notifyListeners();
  43. }
  44.  
  45. void updateProduct(Product product) {
  46. _products[_selectedProductIndex!.toInt()] = product;
  47. //_selectedProductIndex = null;
  48. notifyListeners();
  49. }
  50.  
  51. void deleteProduct() {
  52. _products.removeAt(_selectedProductIndex!.toInt());
  53. //_selectedProductIndex = null;
  54. notifyListeners();
  55. }
  56.  
  57. void toggleProductFavoriteStatus() {
  58. final bool isCurrenltyFavorite = selectedProduct.isFavourite;
  59.  
  60. final bool newFavoriteStatus = !isCurrenltyFavorite;
  61.  
  62. final Product updateProduct = Product(
  63. title: selectedProduct.title,
  64. description: selectedProduct.description,
  65. price: selectedProduct.price,
  66. image: selectedProduct.image,
  67. isFavourite: newFavoriteStatus);
  68. _products[selectedProductIndex] = updateProduct;
  69. notifyListeners();
  70. }
  71.  
  72. void selectProduct(int index) {
  73. _selectedProductIndex = index;
  74. notifyListeners();
  75. }
  76.  
  77. void toggleDisplayMode() {
  78. _showFavorites = !_showFavorites;
  79. notifyListeners();
  80. }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement