I want to create a custom wrapper as AsyncValue<T>
that can hold an asynchronous state (loading
, data
, error
) and be used in a Cubit state class.
The goal is to avoid creating multiple Cubits for handling different async tasks and instead manage them within a single state/cubit class.
Desired Implementation:
final AsyncValue<int> counter = AsyncValue<int>(1);
// Expected state handling methods
counter.loading();
counter.setData(1);
counter.setError();
Use Case in Cubit:
class CounterState {
final AsyncValue<int> counter1;
final AsyncValue<int> counter2;
CounterState({required this.counter1, required this.counter2});
CounterState copyWith({AsyncValue<int>? counter1, AsyncValue<int>? counter2}) {
return CounterState(
counter1: counter1 ?? this.counter1,
counter2: counter2 ?? this.counter2,
);
}
}
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(CounterState(counter1: AsyncValue.data(0), counter2: AsyncValue.data(0)));
Future<void> updateCounter1() async {
emit(state.copyWith(counter1: AsyncValue.loading()));
await Future.delayed(Duration(seconds: 1));
emit(state.copyWith(counter1: AsyncValue.data(1)));
emit(state.copyWith(counter1: AsyncValue.error('Failed to fetch counter1')));
}
Future<void> updateCounter2() async {
emit(state.copyWith(counter2: AsyncValue.loading()));
await Future.delayed(Duration(seconds: 1));
emit(state.copyWith(counter2: AsyncValue.data(2)));
emit(state.copyWith(counter2: AsyncValue.error('Failed to fetch counter2')));
}
}
Question:
How can I create the AsyncValue<T>
class so that it supports the required states (loading
, data
, error
) and integrates well with Cubit?
Would this approach be considered an anti-pattern in the Cubit architecture?