Auto-Dispose

  • 它是一个非常简易管理生命周期对象的方式。一个 auto-dispose 对象可以自我主动释放,或者在它 follow 的 托管对象释放的时候,释放。
  • 在 Effect 中使用的 Context,以及 HigherEffect 中的 EffectPart,都是 auto-dispose 对象。所以我们可以方便的将自定义的需要做生命周期管理的对象托管给它们。
  • 示例代码
  1. class ItemWidgetBindingObserver extends WidgetsBindingObserver
  2. with AutoDispose {
  3. ItemWidgetBindingObserver() : super() {
  4. WidgetsBinding.instance.addObserver(this);
  5. }
  6. @override
  7. void didChangeAppLifecycleState(AppLifecycleState state) {
  8. if (AppConfig.flutterBinding.framesEnabled &&
  9. state == AppLifecycleState.resumed) {
  10. AppConfig.flutterBinding.performReassemble();
  11. }
  12. }
  13. @override
  14. void dispose() {
  15. super.dispose();
  16. WidgetsBinding.instance.removeObserver(this);
  17. }
  18. }
  19. void _init(Action action, Context<ItemPageContainerState> ctx) {
  20. final ItemWidgetBindingObserver observer = ItemWidgetBindingObserver();
  21. observer.follow(ctx);
  22. }