【问题标题】:List view cards doesn't work after adding if condition inside in flutter在颤振中添加if条件后,列表视图卡不起作用
【发布时间】:2020-11-21 21:51:45
【问题描述】:

我的列表视图卡没有返回特定用户存储的所有项目,我想获取用户存储的所有产品

 body: (products != null)
        ? ListView.builder(
            itemCount: products.length,
            itemBuilder: (context, index) {
              if (products[index].ownerId == user.uid) {
                return Card(
                  child: ListTile(
                    leading: Image.asset('graphics/broccoli.png'),
                    title: Text(products[index].name),
                    subtitle:
                        Text(products[index].price.toString() + " Rs"),
                    trailing: Icon(Icons.more_vert),
                  ),
                );
              } else {
                return null;
              }
            })
        : Center(child: CircularProgressIndicator()));

【问题讨论】:

  • 能否提供问题中products函数的代码?

标签: firebase flutter listview flutter-listview


【解决方案1】:

else 部分,返回SizedBox() 而不是null

} else {
  return const SizedBox();
}

这是因为任何小部件的构建方法或构建器函数必须始终返回Widget,而null 不是Widget

所以每当我们想要显示“无”或“空小部件”时,我们可以简单地返回一个SizedBox()

【讨论】:

    【解决方案2】:

    既然Jigar's answer 很贴切,我想给你一些精确的方法来做到这一点。

    • 你也可以返回Container(),它基本上是用来显示空容器的。
    • 您可以只按照您的第一种技术,即使用ternary operator 来返回CardContainer,而不是使用检查返回

    你可以这样做:

                   return (products[index].ownerId == user.uid) ? Card(
                      child: ListTile(
                        leading: Image.asset('graphics/broccoli.png'),
                        title: Text(products[index].name),
                        subtitle:
                            Text(products[index].price.toString() + " Rs"),
                        trailing: Icon(Icons.more_vert)
                      )
                    ) : Container();
    

    【讨论】:

    • 尺寸框总是更好的选择,它有专门设计的高度和宽度,容器还有很多其他参数。
    • 是的@jitsm555 我同意,但是只声明Container() 就像没有heightwidthSizedBox() 一样工作得很好。无论如何,感谢您的建议。每次遇到这种情况我都在使用Container(),但肯定会尝试一下
    猜你喜欢
    • 2022-01-23
    • 2021-02-15
    • 2019-11-15
    • 2021-06-13
    • 2020-11-23
    • 2020-06-19
    • 2021-06-28
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多