【发布时间】:2020-11-17 17:07:30
【问题描述】:
我对 Bloc 的新版本有点困惑:6.0.0,添加了 Cubit 概念,bloc 是贬值还是我们可以同时使用它们?
【问题讨论】:
-
Bloc vs Cubit:bloclibrary.dev/#/coreconcepts?id=cubit-vs-bloc
我对 Bloc 的新版本有点困惑:6.0.0,添加了 Cubit 概念,bloc 是贬值还是我们可以同时使用它们?
【问题讨论】:
Cubit 是 BLoC 模式包的一个子集,它不依赖于事件,而是使用方法来发出新的状态。
因此,我们可以将 Cubit 用于简单的状态,并根据需要使用 Bloc。
【讨论】:
Cubit 非常适合任何应用程序规模。没有一个比另一个更好。
您必须在可追溯性和样板之间做出选择。当你使用一个块时,你有一个包含事件的转换:
Transition {
currentState: AuthenticationState.authenticated,
event: LogoutRequested,
nextState: AuthenticationState.unauthenticated
}
当你使用肘时它不会
Transition {
currentState: AuthenticationState.authenticated,
nextState: AuthenticationState.unauthenticated
}
仅此一项即可为您提供可追溯性,因为您只需查看日志即可知道是哪个事件触发了更改。你看到 eventA 发生然后 eventB。但在实践中,对于肘关节,您通常可以从没有“标签”的变化本身推断出可追溯性。
本质上,发出一个动作/事件,然后映射到调用一个函数,就像直接调用函数一样。唯一的根本变化是间接层允许人们在中间做某事。
当你使用一个块时,你必须实现 mapEventToState 方法,你还必须编写你的动作,这是一个主要调用你的函数的间接层。因此,如果您不需要可追溯性,那么这种间接级别是不必要的,您可以直接调用您的函数。
请注意,在 Bloc 的下一版本中,使用“on”方法将显着减少使用 bloc 的样板。
【讨论】:
Cubit 适用于简单的状态管理,您只需将一种事件绑定到状态。而 Bloc 用于复杂的状态管理,您可以将许多事件映射到状态。
例如让我们考虑下面Cubit
class SimpleCubit extends Cubit<SimpleState> {
SimpleCubit () : super(InitialState());
void updateState(String stateName){
emit(NewState(stateName));
}
}
现在让我们看看Bloc
class SimpleBloc extends Bloc<SimpleEvent, SimpleState> {
SimpleBloc() : super(InitialState()){
on<SimpleEven1>(_handleEvent1);
on<SimpleEven2>(_handleEvent2)
}
Future<void> _handleEvent1(SimpleEvent event, Emitter<SimpleState1> emit) async {
// Put your code here
emit(SimpleState1(event.args))
}
Future<void> _handleEvent2(SimpleEvent event, Emitter<SimpleState2> emit) async {
// Put your code here
emit(SimpleState2(event.args))
}
}
要使用Cubit 实现上述代码,我们需要切换案例(样板)
Bloc 强制你将每个事件映射到一个单独的函数,这在你有一个复杂的状态时很好。
【讨论】: