flutter中的Widget唯一ID(标识符)?

538*_*MEO 5 dart flutter

简单的问题我无法找到答案。

我来自 Web 开发人员背景,您可以通过id应该是唯一的来识别 html 中的 UI 组件。我希望在 Flutter 中做同样的事情。

我们如何才能唯一地识别flutter中的widget?


现实世界用例:

我想跟踪显示的组件以及与之交互的组件,以输出有关它们的统计信息并通过它们的 ID 引用它们。


我的研究:

我看到了这个问题:标题准确地描述了我的问题,但不幸的是,描述和响应与我的用例根本不相关

我在 flutter 文档中也找不到任何对此类功能的引用

jer*_*nac 3

您可以简单地使用 GlobalKey()。顾名思义,唯一全局键是在flutter中能够唯一标识一个widget的键。您只需实例化一个,并将其传递给小部件的 \xc2\xab\xc2\xa0key:\xc2\xa0\xc2\xbb 属性。然后你\xe2\x80\x99就可以通过该键访问你的widget\xe2\x80\x99s数据,有点像在html中。

\n
// A widget containing the observed widget and the widget showing stats about it.\nclass ParentWidget extends StatelessWidget {\n  // We initiate the key here.\n  // We want to create the key in a widget that will not be rebuilt, so it does not get reinitialized.\n  final observedWidgetKey = GlobalKey();\n  ParentWidget();\n\n  @override\n  Widget build(BuildContext context) {\n    return Column(\n      // We pass the key to both widgets.\n      children: [ObservedWidget(key: observedWidgetKey), WidgetStats(observedWidgetKey: observedWidgetKey,)],\n    );\n  }\n}\n\n// The widget which we want to observe.\nclass ObservedWidget extends StatelessWidget {\n  // 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.\n  ObservedWidget({required Key key}) : super(key: key);\n\n  @override\n  Widget build(BuildContext context) {\n    return Text("Hello, I am a widget !");\n  }\n}\n\nclass WidgetStats extends StatelessWidget {\n  final GlobalKey observedWidgetKey;\n  WidgetStats({required this.observedWidgetKey});\n\n  @override\n  Widget build(BuildContext context) {\n    // You can access all sorts of information inside the GlobalKey, this is just an example of what you could do.\n    return Text(\n        "Some data about the observed widget: ${observedWidgetKey.currentWidget?.toString()}");\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

因此,在这个例子中,我们有 3 个小部件。一个父 ParentWidget() 将初始化该键,显示一些应该观察的小部件 ObservedWidget() ,以及一个显示有关它的统计信息的小部件 StatsWidget()。父级将密钥传递给两个小部件。ObservedWidget() 将键分配给其 key 属性,而 StatsWidget() 显示在 GlobalKey() 中找到的有关观察到的小部件的统计信息。您可以在 GlobalKey() 中访问有关小部件的大量信息,具体取决于您的用例。

\n

这是一个简单的例子。您必须记住的是,密钥应该在不重建的小部件中初始化,因此位于小部件树的顶部。您还可以使用一些状态管理解决方案来初始化密钥并将其保存在安全的地方,以将其与 UI 分离。

\n