PIbd-32_Shabunov_O.A._Mobil.../lib/presentation/favourites_bloc/favourites_bloc.dart

50 lines
1.4 KiB
Dart
Raw Normal View History

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(
favouritesIds: data,
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(
favouritesIds: updatedList,
hasFavouritesLoaded: true,
));
}
}