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 scenario 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!
Fantastic guide. super readable and easy to understand, especially compared to other articles on Global keys in flutter. This was very helpful with what I was working on.
hi,
im getting “The getter ‘currentState’ isn’t defined for the type…”
what should i do ?
thank you
Maybe don’t use superlongcomplicated names for your classes, and just use A and B, which would be much less confusing to understand.
Calling a method of child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Instead of calling a method of the child, you just call