佛山建站平台,徐州列表网,wordpress先页面再首页,锦州网站建设推广标题在Flutter中#xff0c;父组件可以通过GlobalKey来引用子组件#xff0c;并调用子组件的方法。以下是一个简单的例子#xff1a;
在这个例子中#xff0c;ParentComponent 有一个GlobalKey#xff0c;它被传递给了ChildComponent。当按钮被点击时#xff0c;通过chi…标题在Flutter中父组件可以通过GlobalKey来引用子组件并调用子组件的方法。以下是一个简单的例子
在这个例子中ParentComponent 有一个GlobalKey它被传递给了ChildComponent。当按钮被点击时通过childKey.currentState我们调用了ChildComponent状态中的doSomething方法。
1.首先定义一个子组件并且在其状态中定义一个方法
import package:flutter/material.dart;
class ChildComponent extends StatefulWidget {final GlobalKey key;ChildComponent({this.key}) : super(key: key);override_ChildComponentState createState() _ChildComponentState();
}class _ChildComponentState extends StateChildComponent {void doSomething() {print(Doing something in the child component.);}overrideWidget build(BuildContext context) {return Container(); // 子组件的构建代码}
}在父组件中创建一个GlobalKey并将其传递给子组件
import package:flutter/material.dart;class ParentComponent extends StatefulWidget {override_ParentComponentState createState() _ParentComponentState();
}class _ParentComponentState extends StateParentComponent {final GlobalKey_ChildComponentState childKey GlobalKey();overrideWidget build(BuildContext context) {return Column(children: Widget[ChildComponent(key: childKey),RaisedButton(onPressed: () childKey.currentState.doSomething(),child: Text(Call Child Method),),],);}
}