You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新版Flutter BLoC如何访问state内的自定义状态属性值?

报错原因

你遇到的报错本质是类型不匹配导致的:wishlist是状态子类WishlistLoaded的独有属性,父类WishlistState并未定义该属性。即便你通过if (state is WishlistLoaded)做了类型判断,由于Bloc的state是基类类型的可变变量,Dart不会对可变变量做自动类型提升,直接调用state.wishlist就会触发不存在该getter的报错。


解决方法

  1. 给事件处理函数的参数补全明确类型,避免dynamic类型导致的额外编译问题
  2. 在确认状态为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:09:03