Flutter – InheritedWidget – dispose. 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class BlocHolder extends StatefulWidget { final Widget child; BlocHolder({this.child}); @override _BlocHolderState createState() => _BlocHolderState(); } class _BlocHolderState extends State<BlocHolder> { 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() { } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.