You can simply use a GlobalKey(). As its name suggests a unique global key is a key that can uniquely identify a widget in flutter. You just have to instantiate one, and pass it to the « key: » property of a widget. And you’re then able to access your widget’s data through that key, kind of like in html.
// A widget containing the observed widget and the widget showing stats about it.
class ParentWidget extends StatelessWidget {
// We initiate the key here.
// We want to create the key in a widget that will not be rebuilt, so it does not get reinitialized.
final observedWidgetKey = GlobalKey();
ParentWidget();
@override
Widget build(BuildContext context) {
return Column(
// We pass the key to both widgets.
children: [ObservedWidget(key: observedWidgetKey), WidgetStats(observedWidgetKey: observedWidgetKey,)],
);
}
}
// The widget which we want to observe.
class ObservedWidget extends StatelessWidget {
// Here we pass the key to the super constructor, meaning we assign it to the "key" property of the widget, a property that is present in all widgets in flutter.
ObservedWidget({required Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text("Hello, I am a widget !");
}
}
class WidgetStats extends StatelessWidget {
final GlobalKey observedWidgetKey;
WidgetStats({required this.observedWidgetKey});
@override
Widget build(BuildContext context) {
// You can access all sorts of information inside the GlobalKey, this is just an example of what you could do.
return Text(
"Some data about the observed widget: ${observedWidgetKey.currentWidget?.toString()}");
}
}
So, in this example, we have 3 widgets. One parent ParentWidget() will initialize the key, display some widget ObservedWidget() that should be observed, and a widget that shows stats about it StatsWidget(). The parent passes down the key to both widgets. The ObservedWidget() assigns the key to its key property while the StatsWidget() displays stats about the observed widget, that it found in the GlobalKey(). There are a lot of information about a widget that you can access in the GlobalKey(), depending on your usecase.
This is a simple example. What you have to remember is that the key should be initialized in a widget that does not rebuild, so at the top of you widgets tree. You could also use some state management solutions to initialise and keep your keys somewhere safe, to decouple it from your UI.