简体   繁体   中英

How to call method in child component from parent in flutter?

I have a parent and a child component. An example is below:

class Parent extends StatefulWidget {
  const Parent({Key? key}) : super(key: key);

  @override
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  int stateVar = 1;

  return Container(
    child: Column(
      children: [
        FlatButton(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
          onPressed: () {
            setState() {
              stateVar = stateVar + 1;
              }
            }
          ),
         Child()
        ]
      )
    )
}

And the child component is:

class Child extends StatefulWidget {
  const Child({Key? key}) : super(key: key);

  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {

  methodToCall() {
    print("Method called");
  }

  return Container(
    child: Text("Child text")
    )
}

I want to call the method methodToCall inside the childcomponent from the parent component whenever the value of state variable stateVar changes in the parent.

Doing some research online, I found one way to do it is using GlobalKey as in the blog: https://stacksecrets.com/flutter/how-to-call-method-of-a-child-widget-from-parent-in-flutter

But this is not working, as the two components are in different files, and difficult to handle keys. One other method was to use useEffect but that didn't work. Can someone please help?

You can make your Parent class extending ChangeNotifier and make Children class listening to Parent notifications.

See https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple#changenotifier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM