bloc_network 1.0.1 bloc_network: ^1.0.1 copied to clipboard
A dart package to bootstrap using bloc state management for network requests.
powered by
A supporting package for the bloc ecosystem, which helps reduce boilerplate, when it comes building blocs for managing the state of network requests. It is designed to be fully compatible with the flutter_bloc widgets and APIs, while providing an opinionated and consistent standard of managing network operations.
Features #
Helps bootstrap building blocs for:
- query-like network requests by sub-classing
QueryBloc
orQueryCubit
- mutation-like network requests by sub-classing
MutationBloc
orMutationCubit
For both cases, this package provides pre-defined states and state transitions.
Usage #
- Import the
bloc_network
package and construct a bloc for a network operation, by specifying arepositoryCallback
. It is recommended for the network request to go through the repository pattern:
import 'package:bloc_network/bloc_network.dart';
class CostCubit extends QueryCubit<int> {
@override
Future<int> repositoryCallback(Object? extra) async {
// Simulate an asynchronous operation. Typically this would be the place
// to do something like an HTTP GET request.
await Future<void>.delayed(const Duration(seconds: 1));
return 5;
}
}
- Optionally, provide type aliases for the state of the network request:
typedef CostState = QueryState<int>;
typedef CostLoading = QueryLoading<int>;
typedef CostError = QueryError<int>;
typedef CostAvailable = QuerySuccess<int>;
- Use the bloc:
// assuming the bloc is made available to the widget tree via BlocProvider:
@override
void initState() {
super.initState();
// trigger the network request:
context.read<CostCubit>().fetchData();
}
@override
Widget build(BuildContext context) {
// react to the state of the network request:
return BlocBuilder<CostCubit, CostState>(
builder: (context, state) {
if (state is CostError) {
return Text('Something went wrong! Please retry.');
}
if (state is CostAvailable) {
return Text('The cost for this item is ${state.data}');
}
return Text('Loading...')
},
);
}