BaseCubit<State extends BaseStateI> class
abstract
Base class for Cubit pattern implementation
Provides a foundation for implementing Cubit pattern with built-in error handling and safe async operations. Cubits are simpler than BLoCs as they don't use events.
Features:
- Automatic error state management
- Safe async operations with error catching
- Two error handling strategies (with and without error state)
- Optional failure callbacks for custom error handling
Usage:
class MyCubit extends BaseCubit<MyState> {
MyCubit() : super(MyState.initial());
Future<void> fetchData() async {
final result = await safeAction(
() => apiService.getData(),
failureCall: (error) => print('Failed: $error'),
);
if (result != null) {
emit(state.copyWith(data: result));
}
}
}
Constructors
- BaseCubit(State initialState)
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- isClosed → bool
-
Whether the bloc is closed.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- state → State
-
The current state.
no setterinherited
-
stream
→ Stream<
State> -
The current stream of states.
no setterinherited
Methods
-
addError(
Object error, [StackTrace? stackTrace]) → void -
Reports an
errorwhich triggersonErrorwith an optional StackTrace.inherited -
close(
) → Future< void> -
Closes the instance.
This method should be called when the instance is no longer needed.
Once
closeis called, the instance can no longer be used.inherited -
emit(
State state) → void -
Updates the
stateto the providedstate.emitdoes nothing if thestatebeing emitted is equal to the currentstate.inherited -
handleError(
BaseException message) → void - Handles errors with automatic state emission
-
handleError2(
BaseException message) → void - Handles errors without emitting error state
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onChange(
Change< State> change) → void -
Called whenever a
changeoccurs with the givenchange. Achangeoccurs when a newstateis emitted.onChangeis called before thestateof thecubitis updated.onChangeis a great spot to add logging/analytics for a specificcubit.inherited -
onError(
Object error, StackTrace stackTrace) → void -
Called whenever an
erroroccurs and notifiesBlocObserver.onError.inherited -
safeAction<
T> (AsyncValueGetter< T> callback, {ValueChanged<BaseException> ? failureCall}) → Future<T?> - Executes an async operation with automatic error handling
-
safeAction2<
T> (AsyncValueGetter< T> callback) → Future<T?> - Executes an async operation with minimal error handling
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited