PMU_PIbd32_Kamcharova_K.A/lib/bloc/bloc.dart
2024-12-10 13:41:28 +04:00

56 lines
1.7 KiB
Dart
Raw 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 '../utils/character_service.dart';
import '../models/character.dart';
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.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 CharacterService characterService;
HomeBloc(this.characterService) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
// Внутри HomeBloc, когда получаем данные
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
emit(state.copyWith(status: HomeStatus.loading));
try {
// Получаем список объектов CharacterDTO
final charactersDTO = await characterService.getCharacters(search: event.searchQuery);
// Преобразуем список Character в список CharacterDTO
final charactersAsDTO = charactersDTO.map((character) => character.toDTO()).toList();
emit(state.copyWith(status: HomeStatus.loaded, characters: charactersAsDTO)); // Передаем в emit
} catch (e) {
print('Error: $e');
emit(state.copyWith(status: HomeStatus.error, errorMessage: e.toString()));
}
}
}