import 'package:flutter_android_app/presentation/currency_bloc/currency_events.dart'; import 'package:flutter_android_app/presentation/currency_bloc/currency_state.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:shared_preferences/shared_preferences.dart'; class CurrencyBloc extends Bloc { static const String _currencyPrefsKey = 'local_currency'; static const List _availableCurrencyIds = ['usd', 'rub']; static final String _defaultCurrencyId = _availableCurrencyIds[0]; CurrencyBloc() : super(const CurrencyState()) { on(_onLoadLocalCurrency); on(_onToggleLocalCurrency); } Future _onLoadLocalCurrency( LoadLocalCurrencyEvent event, Emitter emit ) async { emit(state.copyWith( hasCurrencyLoaded: false, )); final prefs = await SharedPreferences.getInstance(); final data = prefs.getString(_currencyPrefsKey); String currencyId = ''; if (data != null) { currencyId = data; } else { currencyId = _defaultCurrencyId; } emit(state.copyWith( currencyId: currencyId, hasCurrencyLoaded: true, )); } Future _onToggleLocalCurrency( ToggleLocalCurrencyEvent event, Emitter emit ) async { if (state.currencyId == null) { return; } final int oldCurrencyIdIdx = _availableCurrencyIds.indexOf(state.currencyId!); int newCurrencyIdIdx = oldCurrencyIdIdx + 1; if (newCurrencyIdIdx >= _availableCurrencyIds.length){ newCurrencyIdIdx = 0; } final newCurrencyId = _availableCurrencyIds[newCurrencyIdIdx]; final prefs = await SharedPreferences.getInstance(); prefs.setString(_currencyPrefsKey, newCurrencyId); emit(state.copyWith( currencyId: newCurrencyId, )); } }