可以获取子控件state、widget、context
class APPHomePage extends StatefulWidget {
@override
_APPHomePageState createState() => _APPHomePageState();
}
class _APPHomePageState extends State<APPHomePage> {
final GlobalKey<_TestChildState> testChildKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
body: TestChild(key: testChildKey),
floatingActionButton: FloatingActionButton(onPressed: (){
print(testChildKey.currentState.widget.name);//获取子控件数据
print(testChildKey.currentState.message);//获取子控件state中的数据
testChildKey.currentState.test();//调用子控件方法
}),
);
}
}
子widget
class TestChild extends StatefulWidget {
final String name = "cy";
TestChild({Key key}):super(key : key);
@override
_TestChildState createState() => _TestChildState();
}
class _TestChildState extends State<TestChild> {
final String message = "hello world";
@override
Widget build(BuildContext context) {
return Container(
child: Text("data"),
);
}
void test(){
print("test");
}
}
打印:
flutter: cy
flutter: hello world
flutter: test
网友评论