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

Flutter Bloc发送ViewModel对象:点击值未更新问题求助

问题原因及解决办法

你的代码里有两个关键问题导致UI不更新:

  1. 状态修改后没赋值,state.selectedColorIndex + 1只是做了计算,但没把结果存回变量里,等于白算。
  2. Bloc要求状态是不可变对象,直接修改现有state再emit,Bloc会判定前后状态是同一个实例,不会触发UI重建。

修复步骤:

1. 把MainViewModel改成不可变类,添加copyWith方法

修改main_view_model.dart:

class MainViewModel {
  final int selectedColorIndex;

  MainViewModel({this.selectedColorIndex = -1});

  // 生成新实例的copyWith方法
  MainViewModel copyWith({int? selectedColorIndex}) {
    return MainViewModel(
      selectedColorIndex: selectedColorIndex ?? this.selectedColorIndex,
    );
  }
}

2. 修改CounterBloc的事件处理逻辑

不再直接修改原state,而是通过copyWith生成新的状态实例:

class CounterBloc extends Bloc<CounterEvent, MainViewModel> {
  CounterBloc() : super(MainViewModel()) {
    on<CounterIncrementPressed>((event, emit) {
      // 计算新值,通过copyWith生成新实例
      final newIndex = state.selectedColorIndex + 1;
      emit(state.copyWith(selectedColorIndex: newIndex));
    });
    on<CounterDecrementPressed>((event, emit) {
      final newIndex = state.selectedColorIndex - 1;
      emit(state.copyWith(selectedColorIndex: newIndex));
    });
  }
}

这样修改后,每次点击按钮都会生成新的MainViewModel实例,Bloc检测到状态变化就会触发BlocBuilder重建UI,界面上的数值就会正常更新了。

内容的提问来源于stack exchange,提问作者GHH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:57:47