|
| 1 | +import 'package:flutter_bloc/flutter_bloc.dart'; |
| 2 | +import 'package:moviesdb/src/blocs/base_bloc/base.dart'; |
| 3 | +import 'package:moviesdb/src/blocs/blocs.dart'; |
| 4 | +import 'package:moviesdb/src/locator.dart'; |
| 5 | +import 'package:moviesdb/src/repositories/repositories.dart'; |
| 6 | + |
| 7 | +class FavoriteBloc extends Bloc<BaseEvent, BaseState> { |
| 8 | + final FavoriteRepository repository = locator<FavoriteRepository>(); |
| 9 | + |
| 10 | + @override |
| 11 | + BaseState get initialState => InitState(); |
| 12 | + |
| 13 | + @override |
| 14 | + Stream<BaseState> mapEventToState(BaseEvent event) async* { |
| 15 | + if (event is ClickedFavorite) { |
| 16 | + try { |
| 17 | + yield (LoadingState()); |
| 18 | + final result = await repository.isFavorite(event.movie); |
| 19 | + if (result == true) { |
| 20 | + await repository.deleteFavorite(event.movie); |
| 21 | + yield (NormalState()); |
| 22 | + } else if (result == false) { |
| 23 | + await repository.addFavorite(event.movie); |
| 24 | + yield (FavoriteState()); |
| 25 | + } |
| 26 | + } catch (e) { |
| 27 | + yield (ErrorState(data: e.toString())); |
| 28 | + } |
| 29 | + } else if (event is CheckFavorite) { |
| 30 | + try { |
| 31 | + yield (LoadingState()); |
| 32 | + final result = await repository.isFavorite(event.movie); |
| 33 | + yield (result == true ? FavoriteState() : NormalState()); |
| 34 | + } catch (e) { |
| 35 | + yield (ErrorState(data: e.toString())); |
| 36 | + } |
| 37 | + } else if (event is GetFavorites) { |
| 38 | + try { |
| 39 | + yield (LoadingState()); |
| 40 | + final result = await repository.getFavorites(); |
| 41 | + yield (LoadedState(data: result)); |
| 42 | + } catch (e) { |
| 43 | + yield (ErrorState(data: e.toString())); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments