切换屏幕后多次调用Bloc事件

时间:2020-10-23 12:41:14

标签: flutter bloc flutter-bloc

我有以下底部工具栏小部件,可在其中创建objectBloc:

class _BottomBarState extends State<BottomBar> {
  final UserRepository userRepository;
  ObjectBloc objectBloc;
  ObjectRepository objectRepository;
  SocketRepository socketRepository;

  _BottomBarState({@required this.userRepository}) : assert (userRepository != null) {
    objectRepository = ObjectRepository(userRepository: userRepository);
    objectBloc = ObjectBloc(objectRepository: objectRepository);
    socketRepository = SocketRepository(
        objectBloc: objectBloc, userRepository: userRepository);
  }

   @override
void dispose() {
  objectBloc.close();
  super.dispose();
}
  
  @override
  Widget build(BuildContext context) {
    return BlocProvider<ObjectBloc>(
      create: (context) {
        return objectBloc;
      },

接下来,我将存储库传递到底部栏上方显示的屏幕:

DoorScreen(
                  objectRepository: objectRepository,
                  userRepository: userRepository,
                  socketRepository: socketRepository),

在此屏幕中,我听状态:

 Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: BlocListener<ObjectBloc, ObjectState>(
            listener: (context, state) {
              if (state is ObjectUpdateSucces) {

现在,当我使用调用以下功能的抽屉转到另一个屏幕时:

Navigator.pushNamed(context, '/objects');

如果我从另一个屏幕返回到对象屏幕(底部),则侦听器将收到2次状态。如果我再做3次,依此类推。在我看来,每次我进入底部栏屏幕时都会创建objectBloc,但是在向右切换屏幕时应该将其丢弃吗?

0 个答案:

没有答案