69 lines
2.4 KiB
Dart
69 lines
2.4 KiB
Dart
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<ReactionEvent, ReactionState> {
|
|
ReactionBloc() : super(const ReactionState(likedIds: [], dislikedIds: [])) {
|
|
on<ChangeLikeEvent>(_onChangeLike);
|
|
on<ChangeDislikeEvent>(_onChangeDislike);
|
|
on<LoadReactionsEvent>(_onLoadReactions);
|
|
}
|
|
|
|
Future<void> _onLoadReactions(LoadReactionsEvent event, Emitter<ReactionState> 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<void> _onChangeLike(ChangeLikeEvent event, Emitter<ReactionState> emit) async {
|
|
final updatedLikedList = List<String>.from(state.likedIds ?? []);
|
|
final updatedDislikedList = List<String>.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<void> _onChangeDislike(ChangeDislikeEvent event, Emitter<ReactionState> emit) async {
|
|
final updatedLikedList = List<String>.from(state.likedIds ?? []);
|
|
final updatedDislikedList = List<String>.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,
|
|
));
|
|
}
|
|
}
|