I started using flutter and came accross the problem where I need communication between two widgets of my application. I found InheritedWidget easy and serve this purpose.
Let us make the problem simple.
Concept is simple. First create a StatefulWidget (MyApp/MyAppState) class that has count variable and a method (onTap) that increments the variable count.
In the build method of MyAppState return the InheritedWidget (MyInheritedWidget)
Associate HomePage widget as a child to MyInheritedWidget.
Complete code:
Let us make the problem simple.
- Button in App footer (MyFancyButton ) :On click on button increment the counter
- Counter widget (MyBox): It is in center of App.
Concept is simple. First create a StatefulWidget (MyApp/MyAppState) class that has count variable and a method (onTap) that increments the variable count.
In the build method of MyAppState return the InheritedWidget (MyInheritedWidget)
Associate HomePage widget as a child to MyInheritedWidget.
@override Widget build(BuildContext context) { return new MyInheritedWidget( count: count, onTap: onTap, child: new HomePage(), ); }Now any change in count variable in State widget will result in rebuilding of child widget wherever MyInheritedWidget.
Complete code:
import 'package:flutter/material.dart'; void main() => runApp(new MaterialApp(title: "Count Click App", home: new MyApp())); class MyApp extends StatefulWidget { @override MyAppState createState() { return new MyAppState(); } } class MyAppState extends State<MyApp> { int count = 0; void onTap() { setState(() { count++; }); } @override Widget build(BuildContext context) { return new MyInheritedWidget( count: count, onTap: onTap, child: new HomePage(), ); } } class MyInheritedWidget extends InheritedWidget { final int count; final Function onTap; const MyInheritedWidget({Key key, this.count, this.onTap, child}) : super(key: key, child: child); @override bool updateShouldNotify(MyInheritedWidget oldWidget) { return oldWidget.count != count; } static MyInheritedWidget of(BuildContext context) { return context.inheritFromWidgetOfExactType(MyInheritedWidget); } } class HomePage extends StatelessWidget { HomePage(); @override build(BuildContext context) { return new Scaffold( appBar: new AppBar(backgroundColor: Colors.amber, title: new Text("Count Click Demo")), body: new Center(child: new MyBox()), persistentFooterButtons: <Widget>[ new MyFancyButton(), ], ); } } class MyBox extends StatelessWidget { @override Widget build(BuildContext context) { return new Center( child: new Text( "Counter: " + MyInheritedWidget.of(context).count.toString(), style: new TextStyle(fontWeight: FontWeight.w900, fontSize: 34.0), ), ); } } class MyFancyButton extends StatelessWidget { @override Widget build(BuildContext context) { return new RaisedButton( onPressed: () { MyInheritedWidget.of(context).onTap(); }, child: new Text("Click Me"), color: Colors.red, textColor: Colors.white, ); } }