【发布时间】:2020-03-26 21:31:23
【问题描述】:
我正在制作 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())),
),
【问题讨论】: