Flutter中使用GlobalKey获取子widget中数据
2020-12-04 本文已影响0人
刘铁崧
可以获取子控件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