在我的Flutter应用程序中“多个小部件使用相同的GlobalKey”

gblwokeq  于 2023-03-24  发布在  Flutter
关注(0)|答案(1)|浏览(193)

我希望有人能帮助我。我在Flutter应用程序中有一些有状态的小部件,因为它们是不同的 Jmeter 板。

GlobalKey projectStreamGlobalKey = GlobalKey<_ProjectStreamState>();
var projectStreamWidget = ProjectStream(projectStreamGlobalKey);

class ProjectStream extends StatefulWidget {
  ProjectStream(Key key) : super(key: key) {
  }

  @override
  State<ProjectStream> createState() => _ProjectStreamState();
}

class _ProjectStreamState extends State<ProjectStream> {

  _ProjectStreamState(){
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(...);
}
}

当我通过底部菜单切换到相应的屏幕时,我使用以下代码进行操作:

Navigator.of(context).push(MaterialPageRoute(builder: (context) => projectStreamWidget));

过了一段时间,我的Flutter应用程序中突然不断地(几乎每秒)显示“多个小部件使用同一个GlobalKey”的消息。部分来自我根本不活跃的屏幕。例如:

======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Multiple widgets used the same GlobalKey.

The key [LabeledGlobalKey<_ProjectStreamState>#260bd] was used by multiple widgets. The parents of those widgets were:
- Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#83764 NEEDS-PAINT)
- Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#c5788 NEEDS-PAINT)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack:

我是否理解错了,或者我不允许使用这样的有状态小部件?提前感谢您的消息。
尝试使用Stateless Widgets,但由于 Jmeter 板数据,内存变得非常大。

q3aa0525

q3aa05251#

将这一行放在_ProjectStreamState类内部而不是外部:

GlobalKey projectStreamGlobalKey = GlobalKey<_ProjectStreamState>();

相关问题