新版Flutter BLoC如何访问state内的自定义状态属性值?
报错原因
你遇到的报错本质是类型不匹配导致的:wishlist是状态子类WishlistLoaded的独有属性,父类WishlistState并未定义该属性。即便你通过if (state is WishlistLoaded)做了类型判断,由于Bloc的state是基类类型的可变变量,Dart不会对可变变量做自动类型提升,直接调用state.wishlist就会触发不存在该getter的报错。
解决方法
- 给事件处理函数的参数补全明确类型,避免dynamic类型导致的额外编译问题
- 在确认状态为
WishlistLoaded后,将state强转为WishlistLoaded类型再访问wishlist属性,也可以用局部变量接收状态触发Dart的自动类型提升。
修改后的_mapAddWishlistToState代码示例:
void _mapAddWishlistToState(AddWishlistProduct event, Emitter<WishlistState> emit) async { if (state is WishlistLoaded) { // 强转状态为WishlistLoaded类型 final currentState = state as WishlistLoaded; try { emit(WishlistLoaded( wishlist: WishlistModel( products: List.from(currentState.wishlist.products) ..add(event.product)))); } catch (_) {} } }
其余事件处理函数也建议补全参数类型,规范写法参考:
void _mapStartWishlistToState(StartWishlist event, Emitter<WishlistState> emit) async { emit(WishlistLoading()); try { await Future.delayed(const Duration(seconds: 1)); emit(const WishlistLoaded()); } catch (_) {} } void _mapRemoveWishlistProduct(RemoveWishlistProduct event, Emitter<WishlistState> emit) async { if (state is WishlistLoaded) { final currentState = state as WishlistLoaded; try { emit(WishlistLoaded( wishlist: WishlistModel( products: List.from(currentState.wishlist.products) ..remove(event.product)))); } catch (_) {} } }
如果你使用的是Dart 3及以上版本,也可以用模式匹配的写法直接完成类型判断+变量声明,代码更简洁:
void _mapAddWishlistToState(AddWishlistProduct event, Emitter<WishlistState> emit) async { if (state case WishlistLoaded currentState) { try { emit(WishlistLoaded( wishlist: WishlistModel( products: List.from(currentState.wishlist.products) ..add(event.product)))); } catch (_) {} } }
内容的提问来源于stack exchange,提问作者rizky ramadhan
相关产品推荐
相关产品推荐

