2024-12-10 13:04:11 +04:00
|
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
|
|
|
import 'events.dart';
|
|
|
|
|
import 'state.dart';
|
2024-12-10 13:06:37 +04:00
|
|
|
|
import '../utils/character_service.dart';
|
|
|
|
|
import '../models/character.dart';
|
2024-12-10 13:04:11 +04:00
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
|
|
|
|
|
emit(state.copyWith(status: HomeStatus.loading));
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
final characters = await characterService.getCharacters(search: event.searchQuery);
|
|
|
|
|
print('Characters loaded: $characters'); // Отладочный вывод
|
|
|
|
|
emit(state.copyWith(status: HomeStatus.loaded, characters: characters));
|
|
|
|
|
} catch (e) {
|
|
|
|
|
print('Error: $e');
|
|
|
|
|
emit(state.copyWith(status: HomeStatus.error, errorMessage: e.toString()));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|