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