Flutter使用Bloc 8.0.1时报错List<User>不是User类型子类型如何解决
问题原因
- 你调用
state.props的使用逻辑错误:SwipeLoaded的props重写后返回的是[users],也就是props本身是一个外层包装列表,它的第一个元素才是你需要的List<User>类型的用户列表。你直接通过List.from(state.props)复制的是外层列表,这个新列表的元素是List<User>类型,既不符合SwipeLoaded要求的users参数类型,也没法直接删除User类型的event.user,所以触发类型不匹配报错。 - 你仅判断了
state is SwipeLoaded,没有对state做类型转换,无法直接访问SwipeLoaded类中定义的users属性。
修复代码
修改你的Bloc类中的对应逻辑即可:
class SwipeBloc extends Bloc<SwipeEvent, SwipeState> { SwipeBloc() : super(SwipeLoading()) { on<SwipeEvent>( (event, emit) async { if (event is SwipeLeftEvent) { if (state is SwipeLoaded) { try { // 先将state强转为SwipeLoaded类型,拿到内部的用户列表 final currentSwipeState = state as SwipeLoaded; // 复制原有用户列表,删除目标用户后生成新状态 emit(SwipeLoaded(users: List.from(currentSwipeState.users)..remove(event.user))); } catch (_) { // 建议这里可以加个打印排查异常,避免静默出错 print(_.toString()); } } } } ); } }
额外说明
props的设计目的是给Bloc做状态相等判断用的,平时取值优先直接访问状态类中明确定义的字段,不要走props取,逻辑更清晰也不会出现类型错误。
内容的提问来源于stack exchange,提问作者flip
相关产品推荐
相关产品推荐

