最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to Create a Custom Async Wrapper Class for Managing States in Flutter Cubit? - Stack Overflow

programmeradmin6浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论