为什么 GridView.builder returns 元素的高度会扩展,而 ListView.Seperated returns 元素的高度是正常的?
Why does the GridView.builder returns elements expanded in height whereas the ListView.Seperated returns the element with normal height?
我想在横向模式下使用网格视图。所以我使用了 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],
);
},
),
);
}
Gridview 的子项有纵横比。这就是为什么您的项目具有与其宽度相同的高度(首先设置宽度)。更改 gridview 中的纵横比值以获得所需的高度。
我想在横向模式下使用网格视图。所以我使用了 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],
);
},
),
);
}
Gridview 的子项有纵横比。这就是为什么您的项目具有与其宽度相同的高度(首先设置宽度)。更改 gridview 中的纵横比值以获得所需的高度。