54 lines
1.6 KiB
Dart
54 lines
1.6 KiB
Dart
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||
|
|
import '../../../data/repositories/config_repository.dart';
|
||
|
|
import '../../../domain/entities/destino.dart';
|
||
|
|
import 'app_state.dart';
|
||
|
|
|
||
|
|
class AppCubit extends Cubit<AppState> {
|
||
|
|
final ConfigRepository _configRepo = ConfigRepository();
|
||
|
|
|
||
|
|
AppCubit() : super(const AppState());
|
||
|
|
|
||
|
|
Future<void> init() async {
|
||
|
|
emit(state.copyWith(isLoading: true));
|
||
|
|
final destinos = await _configRepo.getDestinos();
|
||
|
|
final activo = await _configRepo.getDestinoActivo();
|
||
|
|
emit(state.copyWith(
|
||
|
|
destinos: destinos,
|
||
|
|
destinoActivo: activo,
|
||
|
|
isLoading: false,
|
||
|
|
));
|
||
|
|
}
|
||
|
|
|
||
|
|
void setIndex(int index) {
|
||
|
|
emit(state.copyWith(currentIndex: index));
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> setDestinoActivo(Destino destino) async {
|
||
|
|
if (destino.id != null) {
|
||
|
|
await _configRepo.setDestinoActivo(destino.id!);
|
||
|
|
emit(state.copyWith(destinoActivo: destino));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> addDestino(Destino destino) async {
|
||
|
|
final id = await _configRepo.insertDestino(destino);
|
||
|
|
final newDestino = destino.copyWith(id: id);
|
||
|
|
final destinos = [...state.destinos, newDestino];
|
||
|
|
emit(state.copyWith(destinos: destinos));
|
||
|
|
if (state.destinoActivo == null) {
|
||
|
|
await setDestinoActivo(newDestino);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> removeDestino(int id) async {
|
||
|
|
await _configRepo.deleteDestino(id);
|
||
|
|
final destinos = state.destinos.where((d) => d.id != id).toList();
|
||
|
|
emit(state.copyWith(destinos: destinos));
|
||
|
|
if (state.destinoActivo?.id == id) {
|
||
|
|
emit(state.copyWith(
|
||
|
|
destinoActivo: destinos.isNotEmpty ? destinos.first : null,
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|