gpt4 book ai didi

flutter - 在构建错误期间调用 setState() 或 markNeedsBuild()

转载 作者:行者123 更新时间:2023-12-03 03:24:38 28 4
gpt4 key购买 nike

我正在制作 BackBtn 类,该类在该应用程序的许多地方使用。

设计是相同的,只是按下时的行为不同。

所以,我想在构造函数中传递函数,当按下按钮时使用它。

但是它显示下面的错误

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building BackBtn(dirty):
flutter: setState() or markNeedsBuild() called during build.
flutter: This Overlay widget cannot be marked as needing to build because the framework is already in the
flutter: process of building widgets. A widget can be marked as needing to be built during the build phase
flutter: only if one of its ancestors is currently building. This exception is allowed because the framework
flutter: builds parent widgets before children, which means a dirty descendant will always be built.
flutter: Otherwise, the framework might not visit this widget during this build phase.
flutter: The widget on which setState() or markNeedsBuild() was called was:
flutter: Overlay-[LabeledGlobalKey<OverlayState>#320d3]
flutter: The widget which was currently being built when the offending call was made was:
flutter: BackBtn

这些是我制作的代码。

class BackBtn extends StatelessWidget{

final Function onPressed;
const BackBtn({ Key key ,this.onPressed}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment(1.0,-1.0),
child: FlatButton(
onPressed: onPressed(),
padding: EdgeInsets.all(50),
child: Image.asset('images/BackIcon.png')
)
);
}
}

BackBtn(
onPressed: () => Navigator.push(context,MaterialPageRoute(
builder: (context) => MyHomePage())),
),

最佳答案

在将 onPressed() 分配给 FlatButton() 时,您正在执行回调。

尝试像这样移除大括号:

class BackBtn extends StatelessWidget{

final Function onPressed;
const BackBtn({ Key key ,this.onPressed}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment(1.0,-1.0),
child: FlatButton(
onPressed: onPressed, // Removed the Braces ()
padding: EdgeInsets.all(50),
child: Image.asset('images/BackIcon.png')
)
);
}
}

长话短说;

当您离开大括号时,它会在构建小部件时立即执行您的 onPressed 处理程序。这意味着您将在构建过程中点击导航器和所有其他内容,而不仅仅是在按下实际按钮时。这会导致您的错误。

关于flutter - 在构建错误期间调用 setState() 或 markNeedsBuild(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136054/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com