Line data Source code
1 : import 'package:bloc/bloc.dart'; 2 : import 'package:flutter/widgets.dart'; 3 : import 'package:flutter_bloc/flutter_bloc.dart'; 4 : import 'package:flutter_bloc_patterns/src/common/view_state.dart'; 5 : 6 : /// Callback function for the data loading state. 7 : typedef LoadingCallback = Widget Function(BuildContext context); 8 : 9 : /// Callback function for a success. The data was fetched and nonnull 10 : /// element was returned. 11 : typedef SuccessCallback<T> = Widget Function(BuildContext context, T data); 12 : 13 : /// Callback function for the data refreshing state. Can only occur after 14 : /// [SuccessCallback]. 15 : typedef RefreshingCallback<T> = Widget Function(BuildContext context, T data); 16 : 17 : /// Callback function for no result. The data was fetched 18 : /// successfully, but a null element was returned. 19 : typedef EmptyCallback = Widget Function(BuildContext context); 20 : 21 : /// Callback function for an error. It contains an [error] that has caused 22 : /// which may allow a view to react differently on different errors. 23 : typedef ErrorCallback = Widget Function( 24 : BuildContext context, 25 : dynamic error, 26 : ); 27 : 28 : class ViewStateBuilder<T, B extends Bloc<dynamic, ViewState>> 29 : extends BlocBuilder<B, ViewState> { 30 0 : ViewStateBuilder({ 31 : Key key, 32 : @required B bloc, 33 : LoadingCallback onLoading, 34 : RefreshingCallback<T> onRefreshing, 35 : SuccessCallback<T> onSuccess, 36 : EmptyCallback onEmpty, 37 : ErrorCallback onError, 38 : BlocBuilderCondition<ViewState> condition, 39 0 : }) : super( 40 : key: key, 41 : bloc: bloc, 42 : condition: condition, 43 0 : builder: (BuildContext context, ViewState state) { 44 0 : if (state is Loading) { 45 0 : return onLoading?.call(context) ?? Container(); 46 0 : } else if (state is Refreshing<T>) { 47 0 : return onRefreshing?.call(context, state.data) ?? Container(); 48 0 : } else if (state is Success<T>) { 49 0 : return onSuccess?.call(context, state.data) ?? Container(); 50 0 : } else if (state is Empty) { 51 0 : return onEmpty?.call(context) ?? Container(); 52 0 : } else if (state is Failure) { 53 0 : return onError?.call(context, state.error) ?? Container(); 54 : } else { 55 0 : return Container(); 56 : } 57 : }, 58 : ); 59 : }