为啥 GridView.builder 返回高度扩展的元素,而 ListView.Seperated 返回具有正常高度的元素?

Posted

技术标签:

【中文标题】为啥 GridView.builder 返回高度扩展的元素,而 ListView.Seperated 返回具有正常高度的元素?【英文标题】:Why does the GridView.builder returns elements expanded in height whereas the ListView.Seperated returns the element with normal height?为什么 GridView.builder 返回高度扩展的元素,而 ListView.Seperated 返回具有正常高度的元素? 【发布时间】:2019-10-17 06:37:08 【问题描述】:

我想将网格视图用于横向模式。所以我使用了 GridView 但所有的 Grid 元素都是垂直展开的。

我什至尝试为 ListView.builder 使用 GridView.builder 将 crossAxisCount 设置为 1 以产生与 ListView.builder 相同的效果,但所有项目都垂直展开。

Widget buildTopNews(BuildContext context) 
  return Container(
    padding: EdgeInsets.only(bottom: 20),
    child: MediaQuery.of(context).orientation == Orientation.portrait
        ? ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) 
              return NewsCard(
                news: topNews[index],
              );
            ,
            itemCount: topNews.length,
            separatorBuilder: (BuildContext context, int index) 
              return SizedBox(
                height: 20,
              );
            ,
          )
        : GridView.builder(
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: topNews.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 20,
            ),
            itemBuilder: (BuildContext context, int index) 
              return NewsCard(
                news: topNews[index],
              );
            ,
          ),
  );

【问题讨论】:

【参考方案1】:

Gridview 的子视图具有纵横比。这就是为什么您的项目具有与其宽度相同的高度(首先设置宽度)。更改网格视图中的纵横比值以获得所需的高度。

【讨论】:

以上是关于为啥 GridView.builder 返回高度扩展的元素,而 ListView.Seperated 返回具有正常高度的元素?的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤动中计算 GridView.builder 的 childAspectRatio

如何阻止 Gridview.builder 的滚动条在颤动中显示

带有 Firebase 实时数据库和 futurebuilder 的 Gridview.builder

为啥jQuery为div的高度返回null?

将 ListView 转换为 ListView.builder

无法使用 CSS 将图像扩展为 100% 的浏览器高度 [重复]