2024-12-17 12:10:42 +04:00
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
|
|
import 'favourites_events.dart';
|
|
|
|
import 'favourites_state.dart';
|
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
|
|
|
|
class FavouritesBloc extends Bloc<FavouritesEvent, FavouritesState> {
|
|
|
|
static const String _likedPrefsKey = 'liked';
|
|
|
|
|
|
|
|
FavouritesBloc() : super(const FavouritesState(favouritesIds: [])) {
|
|
|
|
on<LoadFavouritesEvent>(_onLoadFavouritesIds);
|
|
|
|
on<ChangeFavouriteEvent>(_onChangeFavourite);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _onLoadFavouritesIds(
|
|
|
|
LoadFavouritesEvent event, Emitter<FavouritesState> emit
|
|
|
|
) async {
|
|
|
|
emit(state.copyWith(
|
|
|
|
hasFavouritesLoaded: false,
|
|
|
|
));
|
|
|
|
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
final data = prefs.getStringList(_likedPrefsKey);
|
|
|
|
|
|
|
|
emit(state.copyWith(
|
2024-12-30 11:57:56 +04:00
|
|
|
favouritesIds: data,
|
2024-12-17 12:10:42 +04:00
|
|
|
hasFavouritesLoaded: true,
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _onChangeFavourite(
|
|
|
|
ChangeFavouriteEvent event, Emitter<FavouritesState> emit
|
|
|
|
) async {
|
|
|
|
final updatedList = List<String>.from(state.favouritesIds ?? []);
|
|
|
|
|
|
|
|
if (updatedList.contains(event.id)) {
|
|
|
|
updatedList.remove(event.id);
|
|
|
|
} else {
|
|
|
|
updatedList.add(event.id);
|
|
|
|
}
|
|
|
|
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
prefs.setStringList(_likedPrefsKey, updatedList);
|
|
|
|
|
|
|
|
emit(state.copyWith(
|
2024-12-30 11:57:56 +04:00
|
|
|
favouritesIds: updatedList,
|
2024-12-17 12:10:42 +04:00
|
|
|
hasFavouritesLoaded: true,
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|