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

使用Bloc与Freezed实现单选组初始选中时返回NULL如何解决

问题根因

你的代码存在3个核心错误,共同导致打印输出为NULL、单选框默认不选中:

  1. Bloc的事件处理逻辑仅在接收到对应事件时才会执行,你没有在Bloc初始化时发送启动事件,所以状态一直停留在初始的Initial状态,没有切换到radioClickState
  2. 现有的事件处理逻辑没有匹配事件类型,就算传入事件也无法触发预期的状态变更
  3. state.maybeMap的orElse回调没有返回合法值,匹配不到radioClickState时默认返回空值
修复方案

1. 修正Bloc逻辑(推荐使用新版Bloc的on<事件>注册方式,你用的mapEventToState属于已废弃的旧API)

class NoteBloc extends Bloc<NoteEvent, NoteState> {
  NoteBloc() : super(const NoteState.initial()) {
    // 初始化时直接触发启动事件
    add(const NoteEvent.started());
    // 注册启动事件处理
    on<Started>((event, emit) {
      emit(const NoteState.radioClickState(value: 1));
    });
    // 注册单选点击事件处理(后续点击单选需要用到)
    on<RadioClickEvent>((event, emit) {
      emit(NoteState.radioClickState(value: event.value));
    });
  }
}

如果你坚持要用旧的mapEventToState写法,修正后代码如下:

class NoteBloc extends Bloc<NoteEvent, NoteState> {
  NoteBloc() : super(const NoteState.initial()) {
    add(const NoteEvent.started());
  }

  @override
  Stream<NoteState> mapEventToState(NoteEvent event) async* {
    // 必须先匹配事件类型,再处理逻辑
    yield* event.map(
      started: (_) async* {
        yield const NoteState.radioClickState(value: 1);
      },
      radioClickEvent: (e) async* {
        yield NoteState.radioClickState(value: e.value);
      },
    );
  }
}

2. 修正首页代码

补全maybeMap默认返回值,加上单选点击的事件分发逻辑:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<NoteBloc, NoteState>(
      listener: (context, state) {},
      builder: (context, state) {
        // 统一提取groupValue,orElse返回非1/2的默认值,避免类型错误
        final groupValue = state.maybeMap(
          orElse: () => 0,
          radioClickState: (mstate) => mstate.value,
        );
        print("Print me Please $groupValue");
        return Scaffold(
          body: Column(
            children: [
              Radio<int>(
                value: 1,
                groupValue: groupValue,
                onChanged: (int? value) {
                  if (value != null) {
                    context.read<NoteBloc>().add(NoteEvent.radioClickEvent(value: value));
                  }
                },
              ),
              Radio<int>(
                value: 2,
                groupValue: groupValue,
                onChanged: (int? value) {
                  if (value != null) {
                    context.read<NoteBloc>().add(NoteEvent.radioClickEvent(value: value));
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }
}

修复后首次打开应用就会自动触发Started事件,状态切换为value=1的radioClickState,第一个单选框默认选中,打印输出也会正常显示1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:06:00