Flutter - InheritedWidget - dispose

后端 未结 2 1682
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 03:34

I was wondering if anybody knew a way to know when an InheritedWidget was disposed?

The reason of this question is that I am doing some experiments and I am using an

2条回答
  •  旧巷少年郎
    2020-12-11 03:57

    InheritedWidget behaves the same way as other Widget do. Their lifetime is really short: Usually not longer than one build call.

    If you want to store data for longer, InheritedWidget is not what you want. You'll need a State for that.

    Which also means that ultimately, you can use State's dispose for your bloc dispose.

    class BlocHolder extends StatefulWidget {
      final Widget child;
    
      BlocHolder({this.child});
    
      @override
      _BlocHolderState createState() => _BlocHolderState();
    }
    
    class _BlocHolderState extends State {
      final _bloc = new MyBloc();
    
      @override
      Widget build(BuildContext context) {
        return MyInherited(bloc: _bloc, child: widget.child,);
      }
    
    
      @override
      void dispose() {
        _bloc.dispose();
        super.dispose();
      }
    }
    
    class MyInherited extends InheritedWidget {
      final MyBloc bloc;
    
      MyInherited({this.bloc, Widget child}): super(child: child);
    
      @override
      bool updateShouldNotify(InheritedWidget oldWidget) {
        return oldWidget != this;
      }
    }
    
    
    class MyBloc {
      void dispose() {
    
      }
    }
    

提交回复
热议问题