How To Call Method Of A Child Widget From Parent In Flutter

In this post we will learn how we can call methods of a child widget from a parent widget using GlobalKey.

Introduction

Often times we are faced with a senior where we want to call methods of child widget. Maybe you want to call it’s dispose method or want to update it’s state by calling a function.

Setup

For the purpose of demonstration, let’s create few basic widgets first.

A basic Stateful widget in Flutter looks something like this:

class MyWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return null;
  }

  void myMethodIWantToCallFromAnotherWidget() {
    print('calling myMethodIWantToCallFromAnotherWidget..');
    // actual implementation here
  }
}

Let’s create another widget from where we would be calling the myMethodIWantToCallFromAnotherWidget.

class MyAnotherWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return Container(child: MyWidget());
  }

  void onSomeEvent() {
    // call myMethodIWantToCallFromAnotherWidget from MyWidget
  }
}

So, here we are trying to call the method of MyWidget from MyAnotherWidget. So how can we achieve this Flutter?

Use GlobalKey

In Flutter, GlobalKey helps to uniquely identify the created widgets. With the help of GlobalKey, we can access the State of Flutter widgets hence allowing us to call methods from any child widget.

Now in order to use GlobalKey we need to make a few changes in our code. Firstly, we need to add a Key identifier to our MyWidget constructor.

class MyWidget extends StatefulWidget {
  MyWidget({Key key}) : super(key: key);
...

This allows us to pass a GlobalKey to identify the state of MyWidget when creating an instance of this widget.

final GlobalKey<_MyWidgetState> _myWidgetState = GlobalKey<_MyWidgetState>();

  @override
  Widget build(BuildContext context) {
    return Container(child: MyWidget(key: _myWidgetState));
  }

And finally, we can make use of this key as below:

void onSomeEvent() {
    // call myMethodIWantToCallFromAnotherWidget from MyWidget
    _myWidgetState.currentState.myMethodIWantToCallFromAnotherWidget();
  }

Congratulations you now know how to call methods of child widgets from parent widget!