Infrastructure
A Flutter library for managing API calls using the BLoC pattern. This library provides a set of classes and utilities to simplify API calls and manage state changes.
To use this library, add api_bloc as a dependency in your pubspec.yaml file.
dependencies:
api_bloc: ^1.6.0
Create a subclass of BlocController
with BlocStates
. This library already provides you with FetchStates [loading, success, error] and SubmitStates [idle, loading, success, failed, error], but you can create custom state by extending BlocStates
.
import 'package:api_bloc/api_bloc.dart';
class GetUserController extends FetchController {
@override
Future request({List args = const []}) async {
// make API call
}
}
final controller = GetUserController();
ApiBloc.builder(
controller: controller,
builder: (context, state, child) {
// handle different state scenarios
},
);
import 'package:api_bloc/api_bloc.dart';
class CreateUserController extends SubmitController {
@override
// Specify autoDispose value if needed
@override
Future request({List args = const []}) async {
// make API call
}
}
final controller = CreateUserController();
ApiBloc(
controller: controller,
listener: (context, state) {
// handle different state scenarios
},
builder: (context, state, child) {
// build UI based on state
},
);
Customize how your ApiBloc handles different state scenarios using extensions:
import 'package:api_bloc/api_bloc.dart';
final controller = CreateUserController();
ApiBloc(
controller: controller,
child: TextButton(text: "Create", onPressed: () => controller.run())
)
.onLoading(
builder: (context, state, child) {
// handle loading state
})
.onFailed(
listener: (context, state, child) {
// handle failed state
})
.onSuccess(
listener: (context, state, child) {
// handle success state
})
.onError(
listener: (context, state, child) {
// handle error state
})
.onState>(
listener; (context, state) {
// handle custom state
},
builder: (context, state, child) {
// build UI based on custom state
}
);
Find an example usage of this library in the following links: