我正在借助 bloc(cubit)创建异步计数器应用程序,每次计数器返回 0 时我都会发出加载状态
Posted
技术标签:
【中文标题】我正在借助 bloc(cubit)创建异步计数器应用程序,每次计数器返回 0 时我都会发出加载状态【英文标题】:I am was creating async counter app in flutter with help of bloc (cubit) whet i am emitting a loading state every time counter return to 0 【发布时间】:2021-08-12 05:57:55 【问题描述】:我正在使用 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();
【问题讨论】:
【参考方案1】:问题是您的其他状态不包含具有counter
值的构造函数。因此,使用抽象类的默认值 - 0。为了保持状态,您应该在所有状态中设置计数器值。这是重新编写的状态代码:
@immutable
abstract class CounterState
final int counter;
CounterState(this.counter = 0);
class Counter extends CounterState
// you do not need the counter property here, it is defined in the base class
Counter(required int counter) : super(counter: counter);
class CounterLoading extends CounterState
CounterLoading(required int counter) : super(counter: counter);
class CounterLoaded extends CounterState
CounterLoaded(required int counter) : super(counter: counter);
并相应地调整你的肘:
class CounterCubit extends Cubit<CounterState>
CounterCubit() : super(Counter(counter: 0));
void increment()
print('before CounterLoading() $state.counter');
emit(CounterLoading(counter: state.counter));
print('after CounterLoading() $state.counter');
Timer(Duration(seconds: 2), ()
emit(CounterLoaded(counter: state.counter));
print('enter code hereprevious state $state.counter');
emit(Counter(counter: state.counter + 1));
print('next state $state.counter');
);
【讨论】:
明白。但是正如您所见,有很多代码重复,有没有最简单的方法?是否有必要每次为每个州打一个超级电话? 我重构了状态代码以避免重复。如果你想有单独的状态(加载,加载,计数器),这是一种方法。但是,从您想要实现的目标来看,只有一个具有 counter 属性的 Counter 状态就足够了。 如果状态将超过一个字段,大约 10 个字段假设我应该为每个字段编写超级调用以不丢失当前状态? 如果所有状态共享必须维护的相同属性(属性) - 是的,因为您需要调用super()
来访问基本构造函数。以上是关于我正在借助 bloc(cubit)创建异步计数器应用程序,每次计数器返回 0 时我都会发出加载状态的主要内容,如果未能解决你的问题,请参考以下文章
Flutter BLoC:Cubits 比 BLoC 好吗?
我应该先启动 Cubit,然后再将代码重构为 Bloc 吗?