79 lines
2.0 KiB
Dart
79 lines
2.0 KiB
Dart
import 'package:bloc/bloc.dart';
|
|
import 'package:equatable/equatable.dart';
|
|
import '../../../data/dtos/hero_dto.dart';
|
|
import '../../../data/repositories/hero_repository.dart';
|
|
|
|
// Events
|
|
abstract class HeroSearchEvent extends Equatable {
|
|
@override
|
|
List<Object> get props => [];
|
|
}
|
|
|
|
class SearchHeroes extends HeroSearchEvent {
|
|
final String query;
|
|
|
|
SearchHeroes(this.query);
|
|
|
|
@override
|
|
List<Object> get props => [query];
|
|
}
|
|
|
|
// States
|
|
abstract class HeroSearchState extends Equatable {
|
|
@override
|
|
List<Object> get props => [];
|
|
}
|
|
|
|
class HeroSearchInitial extends HeroSearchState {}
|
|
|
|
class HeroSearchLoading extends HeroSearchState {}
|
|
|
|
class HeroSearchLoaded extends HeroSearchState {
|
|
final List<HeroDto> heroes;
|
|
|
|
HeroSearchLoaded(this.heroes);
|
|
|
|
@override
|
|
List<Object> get props => [heroes];
|
|
}
|
|
|
|
class HeroSearchError extends HeroSearchState {
|
|
final String message;
|
|
|
|
HeroSearchError(this.message);
|
|
|
|
@override
|
|
List<Object> get props => [message];
|
|
}
|
|
|
|
// BLoC
|
|
class HeroSearchBloc extends Bloc<HeroSearchEvent, HeroSearchState> {
|
|
final List<HeroDto> allHeroes;
|
|
|
|
HeroSearchBloc({required this.allHeroes}) : super(HeroSearchInitial()) {
|
|
print('HeroSearchBloc initialized with heroes: ${allHeroes.map((hero) => hero.name).toList()}');
|
|
on<SearchHeroes>((event, emit) {
|
|
print('Search query: ${event.query}');
|
|
if (event.query.isEmpty) {
|
|
emit(HeroSearchInitial());
|
|
return;
|
|
}
|
|
|
|
final queryLower = event.query.toLowerCase().trim();
|
|
final filteredHeroes = allHeroes.where((hero) {
|
|
final nameLower = hero.name.toLowerCase().trim();
|
|
print('Comparing "$queryLower" with "$nameLower"');
|
|
return nameLower.contains(queryLower);
|
|
}).toList();
|
|
|
|
if (filteredHeroes.isEmpty) {
|
|
print('No heroes found for query: ${event.query}');
|
|
emit(HeroSearchError('No heroes found.'));
|
|
} else {
|
|
print('Heroes found: ${filteredHeroes.map((hero) => hero.name).toList()}');
|
|
emit(HeroSearchLoaded(filteredHeroes));
|
|
}
|
|
});
|
|
}
|
|
}
|