繁体   English   中英

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

[英]How to call method in child component from parent in flutter?

我有一个父组件和一个子组件。 一个例子如下:

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()
        ]
      )
    )
}

子组件是:

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")
    )
}

每当父组件中 state 变量stateVar的值发生变化时,我想从父组件调用子组件内的方法methodToCall

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

但这行不通,因为这两个组件位于不同的文件中,并且很难处理密钥。 另一种方法是使用useEffect但它不起作用。 有人可以帮忙吗?

您可以让您的Parent class 扩展ChangeNotifier并让Children class 收听Parent通知。

参见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