import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'reaction_event.dart'; import 'reaction_state.dart'; const String _likedPrefsKey = 'liked'; const String _dislikedPrefsKey = 'disliked'; class ReactionBloc extends Bloc { ReactionBloc() : super(const ReactionState(likedIds: [], dislikedIds: [])) { on(_onChangeLike); on(_onChangeDislike); on(_onLoadReactions); } Future _onLoadReactions(LoadReactionsEvent event, Emitter emit) async { final prefs = await SharedPreferences.getInstance(); final likedData = prefs.getStringList(_likedPrefsKey); final dislikedData = prefs.getStringList(_dislikedPrefsKey); emit(state.copyWith( likedIds: likedData ?? [], dislikedIds: dislikedData ?? [], )); } Future _onChangeLike(ChangeLikeEvent event, Emitter emit) async { final updatedLikedList = List.from(state.likedIds ?? []); final updatedDislikedList = List.from(state.dislikedIds ?? []); if (updatedLikedList.contains(event.id)) { updatedLikedList.remove(event.id); } else { updatedLikedList.add(event.id); updatedDislikedList.remove(event.id); // Убираем дизлайк, если он был } final prefs = await SharedPreferences.getInstance(); prefs.setStringList(_likedPrefsKey, updatedLikedList); prefs.setStringList(_dislikedPrefsKey, updatedDislikedList); emit(state.copyWith( likedIds: updatedLikedList, dislikedIds: updatedDislikedList, )); } Future _onChangeDislike(ChangeDislikeEvent event, Emitter emit) async { final updatedLikedList = List.from(state.likedIds ?? []); final updatedDislikedList = List.from(state.dislikedIds ?? []); if (updatedDislikedList.contains(event.id)) { updatedDislikedList.remove(event.id); } else { updatedDislikedList.add(event.id); updatedLikedList.remove(event.id); // Убираем лайк, если он был } final prefs = await SharedPreferences.getInstance(); prefs.setStringList(_likedPrefsKey, updatedLikedList); prefs.setStringList(_dislikedPrefsKey, updatedDislikedList); emit(state.copyWith( likedIds: updatedLikedList, dislikedIds: updatedDislikedList, )); } }