GlobalKey
可以帮助我们访问某个 Widget
的信息,包括 Widget
或 State
或 Element
等对象
可以在 HomePage
中直接访问 HomeContent
中的内容
class HomePage extends StatelessWidget {
final GlobalKey<_HomeContentState> homeKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("demo"),
),
body: HomeContent(key: homeKey),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.data_usage),
onPressed: () {
print("${homeKey.currentState?.value}");
print("${homeKey.currentState?.widget.name}");
homeKey.currentState?.stateM();
homeKey.currentState?.widget.contentM();
},
),
);
}
}
class HomeContent extends StatefulWidget {
final String name = "HomeContent";
HomeContent({Key? key}) : super(key: key);
@override
_HomeContentState createState() => _HomeContentState();
contentM() {
print("contentM");
}
}
class _HomeContentState extends State<HomeContent> {
final String value = "_HomeContentState";
@override
Widget build(BuildContext context) {
return Container();
}
stateM() {
print("stateM");
}
}
网友评论