使用底部导航器 sheet 且 bloc 仅显示一次

using bottom navigator sheet with bloc showing only once

我创建了一个浮动操作按钮,单击底部 sheet 会弹出。我正在使用带有冻结库的集团。当我在应用程序热重启后粘贴到浮动操作底部时,底部 sheet 应用程序出现,当我再次单击浮动操作按钮时,没有任何操作发生。

集团代码:

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

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

事件代码:

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

州代码:

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

底部sheet代码为:

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

当使用 freezed 类 时,运算符== 执行深度等于,因此您的 bloc 状态的每个实例都等于前一个。在这种情况下,不会发出新状态。您的新状态需要与之前的状态不同。

我通常这样写代码

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

  @override
  Stream<NoteState> mapEventToState(
    NoteEvent event,
  ) async* {
    yield* event.when(
     started: () async*{
        yield initial(),
      },
     addNoteClickedState: ()async*{
        yield addNoteClickedState();
      },
    );
  }
}

它总是有效