我正在使用 BLoC(cubit)在颤振中创建一个异步计数器应用程序。当我发出加载状态时,计数器不会增加而是返回到 0。如何解决这个问题?
代码:
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'counter_state.dart';
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(Counter(counter: 0));
void increment() {
print('before CounterLoading() ${state.counter}');
emit(CounterLoading());
print('after CounterLoading() ${state.counter}');
Timer(Duration(seconds: 2), () {
emit(CounterLoaded());
print('enter code hereprevious state ${state.counter}');
emit(Counter(counter: state.counter + 1));
print('next state ${state.counter}');
});
}
}
part of 'counter_cubit.dart';
@immutable
abstract class CounterState {
final int counter = 0;
}
class Counter extends CounterState {
final int counter;
Counter({this.counter});
}
class CounterLoading extends CounterState {
CounterLoading();
}
class CounterLoaded extends CounterState {
CounterLoaded();
}