Advertisement
multiarts

FavoritesBloc

Dec 24th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.68 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:e_commerce_bloc/bloc/icons_bloc.dart';
  4. import 'package:rxdart/rxdart.dart';
  5.  
  6. import 'package:e_commerce_bloc/models/product.dart';
  7. import 'package:shared_preferences/shared_preferences.dart';
  8.  
  9. class FavoritesBloc {
  10.   Map<String, Product> _favorites = {};
  11.   IconsBloc _iconsBloc;
  12.  
  13.   final _favoritesController = BehaviorSubject<Map<String, Product>>.seeded({});
  14.   Stream<Map<String, Product>> get outFav => _favoritesController.stream;
  15.  
  16.   FavoritesBloc(){
  17.     _iconsBloc = IconsBloc();
  18.     SharedPreferences.getInstance().then((prefs){
  19.       if(prefs.getKeys().contains('favorites')){
  20.         _favorites = json.decode(prefs.getString('favorites')).map((k, v){
  21.           return MapEntry(k, Product.fromJson(v));
  22.         }).cast<String, Product>();
  23.         _favoritesController.add(_favorites);
  24.       }
  25.     });
  26.   }
  27.  
  28.   void toggleFavorites(Product product){
  29.     if(_favorites.containsKey(product.id)) {
  30.       _favorites.remove(product.id);
  31.       _favoritesController.add(_favorites);
  32.       _iconsBloc.notifyFavoriteIcon(true);
  33.       print(_favorites.length);
  34.     } else {
  35.       _favorites[product.id] = product;
  36.       print(_favorites.length);
  37.     }    
  38.  
  39.     _favoritesController.sink.add(_favorites);
  40.  
  41.     _saveFav();
  42.   }
  43.  
  44.   void removeFav(Product product){
  45.     _favorites.remove(product.id);
  46.     _favoritesController.add(_favorites);
  47.     _iconsBloc.notifyFavoriteIcon(true);
  48.     _saveFav();
  49.   }
  50.  
  51.   void _saveFav(){
  52.      SharedPreferences.getInstance().then((prefs){
  53.        prefs.setString('favorites', json.encode(_favorites));
  54.      });
  55.   }
  56.  
  57.  
  58.   void dispose(){
  59.     _favoritesController.close();
  60.   }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement