Skip to content

Commit 53bf7c6

Browse files
committed
feat(account): implement available countries bloc
- Add AvailableCountriesBloc to handle fetching and managing available countries - Include logic to sort countries by name in ascending order - Handle loading, success, and failure states - Support error handling for HTTP exceptions and unexpected errors
1 parent aa132ad commit 53bf7c6

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import 'dart:async';
2+
3+
import 'package:bloc/bloc.dart';
4+
import 'package:core/core.dart';
5+
import 'package:data_repository/data_repository.dart';
6+
import 'package:equatable/equatable.dart';
7+
8+
part 'available_countries_event.dart';
9+
part 'available_countries_state.dart';
10+
11+
class AvailableCountriesBloc
12+
extends Bloc<AvailableCountriesEvent, AvailableCountriesState> {
13+
AvailableCountriesBloc({required DataRepository<Country> countriesRepository})
14+
: _countriesRepository = countriesRepository,
15+
super(const AvailableCountriesState()) {
16+
on<FetchAvailableCountries>(_onFetchAvailableCountries);
17+
}
18+
19+
final DataRepository<Country> _countriesRepository;
20+
21+
Future<void> _onFetchAvailableCountries(
22+
FetchAvailableCountries event,
23+
Emitter<AvailableCountriesState> emit,
24+
) async {
25+
if (state.status == AvailableCountriesStatus.loading ||
26+
state.status == AvailableCountriesStatus.success) {
27+
return;
28+
}
29+
emit(state.copyWith(status: AvailableCountriesStatus.loading));
30+
try {
31+
final response = await _countriesRepository.readAll(
32+
sort: [const SortOption('name', SortOrder.asc)],
33+
);
34+
emit(
35+
state.copyWith(
36+
status: AvailableCountriesStatus.success,
37+
availableCountries: response.items,
38+
clearError: true,
39+
),
40+
);
41+
} on HttpException catch (e) {
42+
emit(
43+
state.copyWith(
44+
status: AvailableCountriesStatus.failure,
45+
error: e.message,
46+
),
47+
);
48+
} catch (e) {
49+
emit(
50+
state.copyWith(
51+
status: AvailableCountriesStatus.failure,
52+
error: 'An unexpected error occurred while fetching countries.',
53+
),
54+
);
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)