【发布时间】:2021-08-20 02:14:05
【问题描述】:
我与 Flutter 合作了很长时间,并且有很多已发布的产品。我从来没有真正喜欢过 BLoC,而是更喜欢使用 Provider 或更高版本的 Riverpod。
我只是不明白那个事件的概念。为什么我们还需要它?而且我很困惑,因为它的实际受欢迎程度...... BLoC 的 Cubit 子类似乎更易于使用,但每个人都一直在说:“Cubit 更简单,但不是那么实用”。但什么是限制?
我什至认为 Cubits 同时更有用也更简单:
- 使用 Cubit,您只需使用参数调用它的方法。如果需要,您仍然可以监听其状态并获取方法返回值。
- 您不需要额外的代码来实现这些事件类型。
- 您不需要额外的代码来实现 bloc 如何处理每个事件类型。方法做得很好。
示例: 用户点击某些产品的“添加到购物车”按钮。
肘:
cartCubit.addProduct(productId);
BLoC:
cartBloc.addEvent(UserAddsProductEvent(productId));
在他们里面:
肘:
void addProduct(String productId) async {
//some validation...
if(...){...}
final result = await cartRepo.addProduct(id);
if(result == ...) {
state = someState;
//....
}
集团:
void addEvent(CartEvent event) {
if (event is UserAddsProductEvent) {
_addProduct(event.productId)
} else if (event is....) {
//.....
}
}
void _addProduct(String productId) async {
//some validation...
if(...){...}
final result = await cartRepo.addProduct(id);
if(result == ...) {
state = someState;
//....
}
重点是什么?
【问题讨论】:
标签: flutter dart bloc state-management