使用 bloc 和 freezed 库创建无线电组的初始状态

creating initial state of radio group using bloc and freezed libraries

我正在使用带冻结库的 bloc。当用户打开应用程序时,我需要选择第一个单选按钮。我已经创建了一个观察者集团,它告诉我初始状态和初始事件已被调用,但是当我打印

print("Print me Please ${state.maybeMap(orElse: () {}, radioClickState: (mstate) => mstate.value)}");

输出为NULL

实现应用层的bloc:

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

  @override
  Stream<NoteState> mapEventToState(
    NoteEvent event,
  ) async* {
   if(state is Initial){
     yield const  NoteState.radioClickState(value:1);
   }
  }
}

活动代码为:

class NoteEvent with _$NoteEvent {
  const factory NoteEvent.started() = Started;
  const factory NoteEvent.radioClickEvent({required  int value} ) =
      RadioClickEvent;
}

州代码是:

class NoteState with _$NoteState {
  const factory NoteState.initial() = Initial;
  const factory NoteState.radioClickState({required int value}) =
      RadioClickState;
}

materialApp里面的代码是:

  home: BlocProvider<NoteBloc>(
    lazy: false,
    create: (context) => NoteBloc(),
    child: const HomePage(),
  ),

广播组实现的首页:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<NoteBloc, NoteState>(
      listener: (context, state) {},
      builder: (context, state) {
      print("Print me Please ${state.maybeMap(
                      orElse: () {}, radioClickState: (mstate) => mstate.value)}");
        return Scaffold(
            // body
            body: Column(
              children: [
                Radio<int>(
                  value: 1,
                  groupValue: state.maybeMap(
                      orElse: () {}, radioClickState: (mstate) => mstate.value),
                  onChanged: (int? value) {},
                ),
                Radio<int>(
                  value: 2,
                  groupValue: state.maybeMap(
                      orElse: () {}, radioClickState: (mstate) => mstate.value),
                  onChanged: (int? value) {},
                ),
              ],
      },
    );
  }
}

您的代码似乎没有向集团添加任何事件。也许这就是问题所在?