Search code examples
flutterblocbottom-sheetflutter-bloc

using bottom navigator sheet with bloc showing only once


I am crated a float action button, on click a bottom sheet will popup. i am using a bloc with freezed library. when i tape to the float action bottom once the application hot restart the bottom sheet app appeared, when i click again on the float action button there is no action happening.

bloc code:

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

  @override
  Stream<NoteState> mapEventToState(
    NoteEvent event,
  ) async* {
    if(event is AddNoteClickedEvent){
      yield const AddNoteClickedState();
    }
  }
}

event code:

@freezed
class NoteEvent with _$NoteEvent {
  const factory NoteEvent.started() = _Started;
  const factory NoteEvent.addNoteClickedEvent() = AddNoteClickedEvent;
}

state code:

@freezed
class NoteState with _$NoteState {
  const factory NoteState.initial() = _Initial;
  const factory NoteState.addNoteClickedState() = AddNoteClickedState;
}

bottom sheet code is:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    return BlocConsumer<NoteBloc, NoteState>(
      listener: (context, state) {
        state.maybeMap(
          orElse: () {},
          addNoteClickedState: (AddNoteClickedState state) {
            return _scaffoldKey.currentState!.showBottomSheet(
              (context) => const AddNewNoteBottomSheet(),
            );
          },
        );
      },
      builder: (context, state) {
        return  Scaffold(
            key: _scaffoldKey,
            floatingActionButton: InkWell(
              onTap: () {
                BlocProvider.of<NoteBloc>(context)
                    .add(const NoteEvent.addNoteClickedEvent());
              },
              child: Icon(
                  Icons.add,
                  // Icons.save,
                  color: const Color(whiteColor),
                  size: 9.h,
        ),
      },
    );
  }
}

Solution

  • When using freezed classes, the operator== performs deep equals, so every instance of your bloc state is equal to the previous. In such a case, a new state won't be emitted. You need your new state to be different than the previous one.