简体   繁体   English

flutter_bloc - 挂钩 onClose、onCreate 特定肘位的生命周期事件

[英]flutter_bloc - hook into onClose, onCreate lifecycle events for specific cubit

I want to hook into the lifecycle events of my cubits.我想与我的肘部的生命周期事件挂钩。

I notice the blocObserver has onClose and onCreate , however that is for observing all cubit's lifecycle events.我注意到 blocObserver 有onCloseonCreate ,但是这是为了观察所有 cubit 的生命周期事件。 How do I hook into these events just for a specific cubit?我如何只针对特定的肘关节来关联这些事件? For example the equivalent of overriding onClose inside a cubit.例如,相当于在一肘内覆盖onClose

My implementation of ChessMax's answer:我对 ChessMax 回答的实现:

class VpCubit<T> extends Cubit<T> {
  VpCubit(T initial) : super(initial);

  void onClose() => print('');

  @override
  Future<void> close() async {
    if (onClose != null) {
      onClose();
    }

    return super.close();
  }
}

class LoggedOutNickNameCubit extends VpCubit<int> {
  LoggedOutNickNameCubit()
      : super(0);

  @override
  void onClose() {
    print('closing');
  }

  void onCreate() {
    print('creating');
  }
}

One possible solution is to filter out events in the observing hook.一种可能的解决方案是过滤掉观察钩子中的事件。 Every event of BlocObserver has a reference to a cubit/bloc instance that sends the event. BlocObserver 的每个事件都有一个对发送事件的 cubit/bloc 实例的引用。 So you can compare it with the reference with your specific cubit/bloc instance.因此,您可以将其与您的特定 cubit/bloc 实例的参考进行比较。 And if references are equal you can handle it somehow.如果引用相等,您可以以某种方式处理它。 Something like this:像这样的东西:

  class MyObserver extends BlocObserver {

  final Cubit<Object> _cubit;

  MyObserver(this._cubit) : assert(_cubit != null);

  @override
  void onClose(Cubit cubit) {
    if (cubit == _cubit) {
      // do whatever you need
    }
    
    super.onClose(cubit);
  }
}

Another way is to create your own cubit/bloc subclass.另一种方法是创建您自己的 cubit/bloc 子类。 Override the methods you want to listen to.覆盖你想听的方法。 And use your own BlocObserver like class to notify this specific cubit/bloc listeners.并使用您自己的 BlocObserver 之类的类来通知此特定的 cubit/bloc 侦听器。 Something like this:像这样的东西:

class MyObserver {
  final void Function() onClose;

  MyObserver(this.onClose);  
}

class MyBloc extends Bloc<MyEvent, MyState> {
  final MyObserver _observer;
  MyBloc(this._observer) : super(MyInitial());


  @override
  Future<void> close() async {
    if (_observer != null && _observer.onClose != null) {
      _observer.onClose();
    }
    
    return super.close();
  }
}

Also, I think, it's possible to write a generic cubit/bloc wrapper base class like above.另外,我认为,可以像上面那样编写通用的 cubit/bloc 包装器基类。 And then use it as a base class for all your cubits/blocs classes instead.然后将其用作所有 cubits/blocs 类的基类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM