简体   繁体   English

flutter如何调用父组件的子组件方法?

[英]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.每当父组件中 state 变量stateVar的值发生变化时,我想从父组件调用子组件内的方法methodToCall

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在网上做了一些研究,我发现一种方法是使用博客中的GlobalKey :https://stacksecrets.com/flutter/how-to-call-method-of-a-child-widget-from-parent-颤动中

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.另一种方法是使用useEffect但它不起作用。 Can someone please help?有人可以帮忙吗?

You can make your Parent class extending ChangeNotifier and make Children class listening to Parent notifications.您可以让您的Parent class 扩展ChangeNotifier并让Children class 收听Parent通知。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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