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

Flutter中点击按钮不显示加载器的Bloc实现问题

解决Cubit中加载器不更新的问题

你当前的问题核心是:直接修改Cubit类里的isLoading成员变量,但没有通过emit方法触发状态更新。BlocBuilder只会在Cubit emit新状态时才会重建UI,所以单纯修改变量值无法让UI感知到变化。

下面是具体的修复步骤:


1. 重构Cubit的状态类

把isLoading字段移到状态类中,让状态承载UI需要的所有数据:

abstract class EditPhotoState {}

// 初始状态,包含加载状态字段
class EditPhotoInitial extends EditPhotoState {
  final bool isLoading;

  EditPhotoInitial({this.isLoading = false});
}

2. 修改Cubit实现

移除Cubit中的isLoading成员变量,添加专门的方法来更新加载状态并emit新状态,同时把上传逻辑整合到Cubit中:

class EditPhotoCubit extends Cubit<EditPhotoState> {
  EditPhotoCubit() : super(EditPhotoInitial(isLoading: false));

  // 更新加载状态的方法
  void _setLoading(bool loading) {
    emit(EditPhotoInitial(isLoading: loading));
  }

  Future<void> uploadImage(String chargingId) async {
    try {
      _setLoading(true);
      // 执行你的图片上传逻辑
      // ...
    } finally {
      // 无论上传成功/失败,都关闭加载状态
      _setLoading(false);
    }
  }
}

3. 更新UI中的BlocBuilder

在BlocBuilder中从状态里读取isLoading,而不是直接访问Cubit的变量:

return BlocBuilder<EditPhotoCubit, EditPhotoState>(
  builder: (context, state) {
    bool isLoading = false;
    if (state is EditPhotoInitial) {
      isLoading = state.isLoading;
    }

    return SizedBox(
      height: size.height,
      width: size.width,
      child: _child(size, topPadding, context, mainState.charging, isLoading),
    );
  },
);

然后修改按钮部分的代码,通过Cubit方法触发上传和状态更新:

SizedBox(
  width: 148,
  child: isLoading
      ? const CircularProgressIndicator(color: constants.Colors.purpleMain)
      : DefaultButtonGlow(
          text: 'Save',
          color: Colors.purpleMain,
          shadowColor: Colors.purpleMain,
          textStyle: Styles.buttonTextStyle,
          onPressed: () async {
            await context.read<EditPhotoCubit>().uploadImage(widget.chargingId);
          },
        ),
),

关键注意事项

  • 永远不要直接修改Cubit的成员变量来更新UI,必须通过emit新状态触发BlocBuilder重建。
  • 业务逻辑(如图片上传)应该放在Cubit中,UI只负责触发事件和根据状态渲染,遵循Bloc单向数据流原则。
  • 使用context.read<EditPhotoCubit>()获取Cubit实例,避免直接持有引用导致的生命周期问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:45:32