Home > Net >  creating initial state of radio group using bloc and freezed libraries
creating initial state of radio group using bloc and freezed libraries

Time:09-17

I am using bloc with freezed libraries. i need when the user open the app the first radio button is chosen. i have been created an observer bloc which tolled me that the initial state and the initial event have been invoked, but when i print

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

the output is NULL.

the bloc which implements the application layer:

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);
   }
  }
}

the event code is:

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

the state code is:

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

the code inside materialApp is:

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

the home page where the radio group implemented:

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) {},
                ),
              ],
      },
    );
  }
}

CodePudding user response:

Your code doesn't seem to add any event to the bloc. Maybe that's the problem?

  • Related