2024-12-20 11:40:46 +04:00

28 lines
1.2 KiB
Dart

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu/presentation/likes_bloc/likes_events.dart';
import 'package:pmu/presentation/likes_bloc/likes_state.dart';
import 'package:shared_preferences/shared_preferences.dart';
const String _likedPrefsKey = 'liked';
class LikeBloc extends Bloc<LikeEvent, LikeState> {
LikeBloc() : super(const LikeState(likedIds: [])) {
on<ChangeLikeEvent>(_onChangeLike);
on<LoadLikesEvent>(_onLoadLikes);
}
Future<void> _onLoadLikes(LoadLikesEvent loadLikesEvent, Emitter<LikeState> emit) async {
final prefs = await SharedPreferences.getInstance();
final data = prefs.getStringList(_likedPrefsKey);
emit(state.copyWith(likedIds: data));
}
Future<void> _onChangeLike(ChangeLikeEvent changeLikeEvent, Emitter<LikeState> emit) async {
final updatedList = List<String>.from(state.likedIds ?? []);
if (updatedList.contains(changeLikeEvent.id)) {
updatedList.remove(changeLikeEvent.id);
} else {
updatedList.add(changeLikeEvent.id);
}
final prefs = await SharedPreferences.getInstance();
prefs.setStringList(_likedPrefsKey, updatedList);
emit(state.copyWith(likedIds: updatedList));
}
}