Line data Source code
1 : import 'package:bloc/bloc.dart'; 2 : import 'package:flutter_bloc_patterns/details.dart'; 3 : import 'package:flutter_bloc_patterns/src/common/view_state.dart'; 4 : import 'package:flutter_bloc_patterns/src/details/details_events.dart'; 5 : import 'package:flutter_bloc_patterns/src/details/details_repository.dart'; 6 : 7 : /// A BLoC that allows to fetch a single element with given identifier. 8 : /// 9 : /// Designed to collaborate with [ViewStateBuilder] for displaying data. 10 : /// 11 : /// Call [loadElement] to fetch an element with given identifier. 12 : /// 13 : /// [T] - the type of the element. 14 : /// [I] - the type of id. 15 : class DetailsBloc<T, I> extends Bloc<DetailsEvent, ViewState> { 16 : final DetailsRepository<T, I> _detailsRepository; 17 : 18 1 : DetailsBloc(DetailsRepository<T, I> detailsRepository) 19 0 : : assert(detailsRepository != null), 20 : this._detailsRepository = detailsRepository; 21 : 22 1 : @override 23 1 : ViewState get initialState => Initial(); 24 : 25 : /// Loads an element with given [id]. 26 3 : void loadElement([I id]) => dispatch(LoadDetails(id)); 27 : 28 : @override 29 1 : Stream<ViewState> mapEventToState(DetailsEvent event) async* { 30 1 : if (event is LoadDetails) { 31 3 : yield* _mapLoadDetails(event.id); 32 : } 33 : } 34 : 35 1 : Stream<ViewState> _mapLoadDetails(I id) async* { 36 : try { 37 2 : yield Loading(); 38 3 : final element = await _detailsRepository.getById(id); 39 3 : yield element != null ? Success<T>(element) : Empty(); 40 1 : } on ElementNotFoundException { 41 2 : yield Empty(); 42 : } catch (e) { 43 2 : yield Failure(e); 44 : } 45 : } 46 : }