Flutter - 无法构建因为框架已经在构建中

27

我正在构建一个页面,动态生成其中的一些视图。在我的情况下,显示的列表将根据用户输入(用作筛选器)进行更新。

当我使用Text Widget进行动态渲染时,一切都完美运行,但是当我尝试切换到Column或Gridview时,所有都出了问题,并且我得到了以下错误:

The following assertion was thrown building ServerGrid(dirty; state: _ServerGridState#59211289()):
I/flutter (14351): setState() or markNeedsBuild() called during build.
I/flutter (14351): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter (14351): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter (14351): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter (14351): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter (14351): Otherwise, the framework might not visit this widget during this build phase.
I/flutter (14351): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (14351):   Overlay([LabeledGlobalKey<OverlayState>#774312152]; state: OverlayState#252339409(entries:
I/flutter (14351):   [OverlayEntry#727022347(opaque: false; maintainState: false), OverlayEntry#1051156104(opaque:
I/flutter (14351):   false; maintainState: true), OverlayEntry#280497357(opaque: false; maintainState: false),
I/flutter (14351):   OverlayEntry#41791024(opaque: false; maintainState: true), OverlayEntry#444321361(opaque: false;
I/flutter (14351):   maintainState: false), OverlayEntry#717668788(opaque: false; maintainState: true)]))

以下是我目前得到的代码,

ServerGrid 是错误发生的地方 import 'package:flutter/material.dart';

import'package:firebase_sandbox/models/server.dart';

class ServerGrid extends StatefulWidget {
  ServerGrid({Key key, this.servers}) : super(key: key);

  final servers;

  @override
  State createState() => new _ServerGridState();
}

class _ServerGridState extends State<ServerGrid> {

  showInfos(serv){
    showDialog(context: context, child: new AlertDialog(content: new Text(serv.toString())));
  }

  Widget buildServerTile(Server serv) {
    return new InkWell(
        onTap: showInfos(serv),
        child :
          new Column(
            children: [
                new CircleAvatar(child : new Image.network(serv.image)),
                new Text(
                  serv.name,
                  style : new TextStyle(fontWeight: FontWeight.bold),
                ),
                new Text(
                  serv.description,
                  style : new TextStyle(color : Colors.grey[500]),
                ),
            ],
          ),
    );
  }

   List<Widget> buildGrid() {
    var theGrid = <Widget>[];
    for(Server s in widget.servers) {
      theGrid.add(buildServerTile(s));
    }
    return theGrid;
  }

  @override
  Widget build(BuildContext context) {
    // return new Text("${widget.servers.toString()}"); //Working perfectly
    return new GridView(
              gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
              ),
               children: buildGrid(),
          );
  }
}

控制器调用视图更新:

  filter(value) {
    filteredList = _servers.where(
            (serv) =>
        serv.name.contains(value) || serv.tags
            .where((tag) => tag.contains(value))
            .length > 0
    ).toList();

    print(filteredList);
    setState(() {
      serverList = new ServerGrid(servers : filteredList);
    });
  }

一直在寻找问题所在,但我无法确定在构建我的GridView时出了什么问题。

3个回答

64
您的onTap处理程序存在问题。它正在尝试在构建函数期间立即显示对话框,这是不允许的。
onTap: showInfos(serv),

将您的处理程序更改为函数:

onTap: () => showInfos(serv),

1
哇...我为自己犯了这么愚蠢的错误感到羞愧。谢谢Collin! - Alexi Coard
1
这是一个非常常见的错误,我也犯过 :) - Collin Jackson
哦,天啊,我因为这个问题已经忙碌了12个小时了... - dasfima
@CollinJackson,每当我在Flutter方面遇到问题时,几乎100%的问题都能通过您的答案得到解决,这一次也是如此。感谢您的天才和帮助。 - shakil.k
4
onTap: showInfos(serv) 和 onTap:=> showInfos(serv) 之间的区别是什么? - M.ArslanKhan
显示剩余6条评论

6

对于那些遇到相同错误但不处于与@Alexi相同的情况下的人,您可以这样做:

WidgetsBinding.instance.addPostFrameCallback((_) {
  // Your code HERE
  // Flutter will wait until the current build is completed before executing this code.
});


3

我使用了另一种有趣的解决方法。现在的情况是在UI构建时通知重新构建UI,导致程序出错。为了解决这个问题,我将其放入Future.delayed()函数中,并给它一个很短的时间间隔,比如1毫秒。

这样做的作用是稍后运行notifylistener,就不会出现任何问题。

显然这不是一个正确的解决方法,但可以帮助解决问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接