【问题标题】:setState() or markNeedsBuild() called during build error在构建错误期间调用 setState() 或 markNeedsBuild()
【发布时间】: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())),
),

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    在将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 处理程序。 这意味着您将在构建过程中点击导航器和所有其他东西,而不仅仅是在按下实际按钮时。这会导致您的错误。

    【讨论】:

    • 我明白了。这是很清楚的解释,我为自己的愚蠢错误感到羞耻。非常感谢。
    • @Robin Reiter 如果 onPressed 不是空函数怎么办?例如 onPressed(index){}
    猜你喜欢
    • 2021-11-14
    • 2021-04-21
    • 2021-12-12
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2020-10-05
    相关资源
    最近更新 更多