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

标签 flutter dart state builder

我收到此错误。 调试控制台中可能发生错误的软件包链接是ResponsiveSafeArea类的构建器功能,如下所示

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building LayoutBuilder:
setState() or markNeedsBuild() called during build.
This _ModalScope<dynamic> widget cannot be marked as needing to build because the framework is
already in the process of building widgets.  A widget can be marked as needing to be built during
the build phase only if one of its ancestors is currently building. This exception is allowed
because the framework builds parent widgets before children, which means a dirty descendant will
always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
  _ModalScope<dynamic>-[LabeledGlobalKey<_ModalScopeState<dynamic>>#e51b7]
The widget which was currently being built when the offending call was made was:
  LayoutBuilder
下面是导致错误的类
class CustSigninView extends StatefulWidget {
  @override
  _CustSigninViewState createState() => _CustSigninViewState();
}

class _CustSigninViewState extends State<CustSigninView> {
  final TextEditingController _phNoController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;

    bool tempBool = true;             <------------ TEMP "BOOL" JUST FOR TESTING
    
   return BaseView<CustSignInViewModel>(
      builder: (context, model, child) => ResponsiveSafeArea(
        builder: (context, widgetSize) => Scaffold(
          body: Material(
            type: MaterialType.card,
            child: Stack(
              children: <Widget>[

             ListView(  //ListView
                
                // --------  I'M GETTING  E R R O R  IN BELOW LINE.
                tempBool
                    ? UIHelper().showErrorButtomSheet(context, "errorText"))
                    : Container(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
如果我在tempBool条件下将UIHelper().showErrorButtomSheet(context, "errorText"))替换为Container(),则可以正常工作。 UIHelper().showErrorButtomSheet(context, "errorText"))存在问题。
下面是showErrorButtomSheet类中的UIHelper函数
  /// Returns a Error Dialog
  Future showErrorButtomSheet(BuildContext context, String errorText) {
    Size deviceSize = MediaQuery.of(context).size;
    return showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        child: StatefulBuilder(
          builder: (BuildContext context, StateSetter stateSetter) {
            return Row(
              children: <Widget>[
                Icon(...),
                Text(...),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
ResponsiveSafeArea类看起来像这样。单击Debug Console中的错误包链接后,重定向到构建器功能
typedef Responsive_Builder = Widget Function(
  BuildContext context,
  Size,
);

class ResponsiveSafeArea extends StatelessWidget {
  final Responsive_Builder responsiveBuilder;

  const ResponsiveSafeArea({
    Key key,
    @required Responsive_Builder builder,
  })  : responsiveBuilder = builder,
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          return responsiveBuilder(
            context,
            constraints.biggest,
          );
        },
      ),
    );
  }
}

最佳答案

Faizan Kamal您正在尝试显示showModalBottomSheet,它无法像其他小部件一样显示。我建议您使用自定义小部件来显示下面的errorText:

Widget showErrorWidget(BuildContext context, String errorText) {
    return Row(
      children: <Widget>[
        Icon(Icons.error),
        Text(errorText),
      ],
    );
  }
并像这样使用它:
...
   tempBool
        ? UIHelper(). showErrorWidget(context, "errorText"))
        : Container(),
   ...
要显示对话框,您必须处理一个事件以实现此目的,例如在布局事件之后:
if(!tempBool)
     Container(), // We display this container when tempBool is false, else we display the dialog
最后添加afterLayout事件:
@override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) => _afterLayout(context));
    super.initState();
...
}

_afterLayout(BuildContext context) async {
    if(tempBool)
        await UIHelper().showErrorButtomSheet(context, "errorText");
}

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

相关文章:

reactjs - 如何使用 React 为映射函数中的各个元素设置状态?

flutter - Flutter中WhatsApp/Telegram类通话功能的实现

postgresql 打开连接并执行多个命令

flutter - 如何从本地文件的目录中导入Dart文件?

flutter - flutter :listview空白分隔线

flutter - 如何刷新屏幕以更新元素列表?

javascript - 使用状态机使我的 UI 简单灵活?好主意?我如何在 Knockout JS 中做到这一点?

javascript - ui-router 中 templateUrl 从一种状态到另一种状态的动态变化

flutter - 如何在 Flutter 中将 setState 发送到第二页?

flutter - Gridview 在 flutter 中在父容器顶部间隔额外区域