Want to correctly use an Inherited Widget in flutter? The thing is: InheritedWidget is just a simple widget that does nothing but holding data. It doesn’t have any logic of update or whatsoever. But, like any other widgets, it’s associated with an Element. And guess what? This thing is mutable and flutter will reuse it whenever possible!
If you understood everything, you should have already guessed the solution :
Wrap your InheritedWidget inside a StatefulWidget that will create a brand new InheritedWidget whenever something changed!
The end result in the actual code would be:
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 43 44 45 46 47 48 | class MyInherited extends StatefulWidget { static MyInheritedData of(BuildContext context) => context.inheritFromWidgetOfExactType(MyInheritedData) as MyInheritedData; const MyInherited({Key key, this.child}) : super(key: key); final Widget child; @override _MyInheritedState createState() => _MyInheritedState(); } class _MyInheritedState extends State<MyInherited> { String myField; void onMyFieldChange(String newValue) { setState(() { myField = newValue; }); } @override Widget build(BuildContext context) { return MyInheritedData( myField: myField, onMyFieldChange: onMyFieldChange, child: widget.child, ); } } class MyInheritedData extends InheritedWidget { final String myField; final ValueChanged<String> onMyFieldChange; MyInheritedData({ Key key, this.myField, this.onMyFieldChange, Widget child, }) : super(key: key, child: child); @override bool updateShouldNotify(MyInheritedData oldWidget) { return oldWidget.myField != myField || oldWidget.onMyFieldChange != onMyFieldChange; } } |
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.