State Manager and Business Logic: Like Bloc

This commit is contained in:
nikbel2004@outlook.com 2024-12-18 17:40:17 +04:00
parent a8fc7288dd
commit f866f2bec2
3 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,40 @@
import 'package:candystore/presentation/bloc/like_bloc/like_event.dart';
import 'package:candystore/presentation/bloc/like_bloc/like_state.dart';
import 'package:flutter_bloc/flutter_bloc.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 event, Emitter<LikeState> emit) async {
final prefs = await SharedPreferences.getInstance();
final data = prefs.getStringList(_likedPrefsKey);
// Преобразуем список строк в список целых чисел
final likedIds = data?.map(int.parse).toList() ?? [];
emit(state.copyWith(likedIds: likedIds));
}
Future<void> _onChangeLike(ChangeLikeEvent event, Emitter<LikeState> emit) async {
final updatedList = List<int>.from(state.likedIds ?? []);
if (updatedList.contains(event.id)) {
updatedList.remove(event.id);
} else {
updatedList.add(event.id);
}
final prefs = await SharedPreferences.getInstance();
// Преобразуем список целых чисел обратно в строки перед сохранением
prefs.setStringList(_likedPrefsKey, updatedList.map((id) => id.toString()).toList());
emit(state.copyWith(likedIds: updatedList));
}
}

View File

@ -0,0 +1,13 @@
abstract class LikeEvent {
const LikeEvent();
}
class LoadLikesEvent extends LikeEvent {
const LoadLikesEvent();
}
class ChangeLikeEvent extends LikeEvent {
final int id;
const ChangeLikeEvent(this.id);
}

View File

@ -0,0 +1,12 @@
import 'package:equatable/equatable.dart';
class LikeState extends Equatable {
final List<int>? likedIds;
const LikeState({required this.likedIds});
LikeState copyWith({List<int>? likedIds}) => LikeState(likedIds: likedIds ?? this.likedIds);
@override
List<Object?> get props => [likedIds];
}