PMU_PIbd32_Kamcharova_K.A/lib/bloc/bloc.dart

78 lines
2.7 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter_bloc/flutter_bloc.dart';
import 'events.dart';
import 'state.dart';
import '../domain/models/character.dart';
import 'dart:async';
import 'package:identity/data/repositories/character_repository.dart';
import 'package:identity/data/dtos/character_dto.dart';
import 'package:identity/data/mappers/character_mapper.dart';
class DebouncedSearchCubit extends Cubit<String> {
DebouncedSearchCubit() : super('');
Timer? _debounce;
// Метод для обновления поиска с задержкой
void search(String query) {
if (_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 500), () {
emit(query);
});
}
@override
Future<void> close() {
_debounce?.cancel();
return super.close();
}
}
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final CharacterRepository characterService;
HomeBloc(this.characterService) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
on<HomeSearchEvent>(_onSearchCharacters);
}
// Загрузка данных
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
emit(state.copyWith(status: HomeStatus.loading));
try {
// Получаем список объектов Character
final characters = await characterService.loadData(searchQuery: event.searchQuery);
if (characters != null) {
// Преобразуем список Character в список CharacterDTO с помощью маппера
final charactersAsDTO = characters.map((character) => CharacterMapper.toDTO(character)).toList();
// Преобразуем обратно в List<Character>
final charactersAsModel = charactersAsDTO.map((dto) => CharacterMapper.fromDTO(dto)).toList();
emit(state.copyWith(status: HomeStatus.loaded, characters: charactersAsModel));
} else {
emit(state.copyWith(status: HomeStatus.error, errorMessage: "Failed to load characters."));
}
} catch (e) {
print('Error: $e');
emit(state.copyWith(status: HomeStatus.error, errorMessage: e.toString()));
}
}
// Логика поиска
void _onSearchCharacters(HomeSearchEvent event, Emitter<HomeState> emit) {
final query = event.query.toLowerCase();
// Фильтруем данные по запросу
final filteredCharacters = state.characters
.where((character) => character.name?.toLowerCase().contains(query) ?? false)
.toList();
// Обновляем состояние с отфильтрованными данными
emit(state.copyWith(status: HomeStatus.loaded, characters: filteredCharacters));
}
}