InheritedWidget is an unbounded functional widget that uses data sharing in the widget tree. Process:

  • Create a class MyInheritedWidget that inherits the InheritedWidget and defines the data to be shared
  • When building the Widget tree, make the MyInheritedWidget the parent class.
  • Custom UI component widgets that internally use the field data of the MyInheritedWidget.
  • When MyInheritedWidget’s data changes, the updateShouldNotify method is called to notify other widgets that depend on MyInheritedWidget, Other widgets call their didChangeDependencies in response.
  • The dependant must be a descendant of the MyInheritedWidget or else the data cannot be shared.

Example: Customize MyInheritedWidget to define shared data

class MyInheritedWidget extends InheritedWidget { final int data; MyInheritedWidget({@required this.data, // Data Widget child,}) : super(child: child); Static MyInheritedWidget of(BuildContext Context) {return context.inheritFromWidgetOfExactType(MyInheritedWidget); } override bool updateShouldNotify(MyInheritedWidget oldWidget) {return true if the data is inconsistent with that of the new widget. The didChangeDependencies method in the child widget is called. Return oldWidget.data! = data; }}Copy the code

Rely on the data in the MyInheritedWidget

class DependWidget extends StatefulWidget { @override DependWidgetState createState() { return new DependWidgetState(); } } class DependWidgetState extends State<DependWidget> { @override Widget build(BuildContext context) { // Return Text(MyInheritedWidget.of(context).data.toString())) using data in the dependent InheritedWidget; } / / when the data in a dependent InheritedWidget changes, this method is called @ override void didChangeDependencies () {super. DidChangeDependencies (); print('change..... '); }}Copy the code

Dependencies change as shared data changes.

class _MyHomePageState extends State<MyHomePage> { int count = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center(child: MyInheritedWidget(data: count,// setState) DependWidget(),// Share data changes affecting the widget),),), floatingActionButton: floatingActionButton (onPressed: () { setState(() { ++count; },); }, child: Icon(Icons.add), ), ); }}Copy the code