How to implement event listener or delegate on flutter How to implement event listener or delegate on flutter dart dart

How to implement event listener or delegate on flutter


You can pass a callback, use the VoidCallback and receive the event on your Main widget.

        class MainPage extends StatelessWidget {          _onTapButton() {            print("your event here");          }          @override          Widget build(BuildContext context) {            return Container(              child: ChildPage(                onTap: _onTapButton,              ),            );          }        }        class ChildPage extends StatelessWidget {          final VoidCallback onTap;          const ChildPage({Key key, this.onTap}) : super(key: key);          @override          Widget build(BuildContext context) {            return Container(              child: RaisedButton(                child: Text("Click Me"),                onPressed: () {                  //call to your callback  here                  onTap();                },              ),            );          }        } 

In case you want the opposite, you can just refresh the state of your parent widget and change the parameter that you pass to your fragments or also you can use GlobalKey, like the example below:

        class MainPage extends StatelessWidget {          final GlobalKey<ChildPageState> _key = GlobalKey();          _onTapButton() {            _key.currentState.myMethod();          }          @override          Widget build(BuildContext context) {            return Container(              child: Column(                children: [                  ChildPage(                    key: _key,                  ),                  RaisedButton(                    child: Text("Click me"),                    onPressed: _onTapButton,                  )                ],              )            );          }        }        class ChildPage extends StatefulWidget {          const ChildPage({Key key}) : super(key: key);          @override          ChildPageState createState() {            return new ChildPageState();          }        }        class ChildPageState extends State<ChildPage> {          myMethod(){            print("called from parent");          }          @override          Widget build(BuildContext context) {            return Container(              child: Text("Click Me"),            );          }        }