我正在制作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())),
),
答案 0 :(得分:2)
将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')
)
);
}
}
Tldr;
当离开括号时,它将在构建窗口小部件时立即执行onPressed处理程序。 这意味着您将在构建过程中点击导航器和所有其他内容,而不仅仅是按下实际按钮时。那会导致您的错误。