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

62 lines
1.8 KiB
Dart

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<CurrencyEvent, CurrencyState> {
static const String _currencyPrefsKey = 'local_currency';
static const List<String> _availableCurrencyIds = ['usd', 'rub'];
static final String _defaultCurrencyId = _availableCurrencyIds[0];
CurrencyBloc() : super(const CurrencyState()) {
on<LoadLocalCurrencyEvent>(_onLoadLocalCurrency);
on<ToggleLocalCurrencyEvent>(_onToggleLocalCurrency);
}
Future<void> _onLoadLocalCurrency(
LoadLocalCurrencyEvent event, Emitter<CurrencyState> 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<void> _onToggleLocalCurrency(
ToggleLocalCurrencyEvent event, Emitter<CurrencyState> 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,
));
}
}