You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter 如何在 GridView 中实现可滚动的双行多列布局

双行横向滚动布局实现方案

你所需的两行多列可横向滚动的布局可通过CSS直接实现,不需要引入额外第三方库,以下是两种常用实现方案:

方案1:CSS Grid 实现(推荐)

Grid布局是实现该需求最简洁的方案,现代浏览器均支持:

代码示例

<!-- HTML 结构 -->
<div class="double-row-scroll">
  <div class="item">卡片1</div>
  <div class="item">卡片2</div>
  <div class="item">卡片3</div>
  <div class="item">卡片4</div>
  <!-- 按需添加更多卡片 -->
</div>
/* CSS 样式 */
.double-row-scroll {
  display: grid;
  /* 固定展示2行,行高等分 */
  grid-template-rows: repeat(2, 1fr);
  /* 强制内容按列排列,超出后横向延伸 */
  grid-auto-flow: column;
  /* 开启横向滚动,隐藏纵向溢出 */
  overflow-x: auto;
  overflow-y: hidden;
  /* 可选:开启平滑滚动对齐 */
  scroll-snap-type: x mandatory;
  /* 卡片间距 */
  gap: 12px;
  padding: 16px;
}

.item {
  /* 自定义卡片尺寸,根据需求调整 */
  width: 120px;
  height: 80px;
  /* 可选:滚动时自动对齐卡片边缘 */
  scroll-snap-align: start;
  background: #f5f5f5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

方案2:Flex 布局实现(兼容性更强)

如果需要兼容更低版本的浏览器,可以用双层Flex容器实现:

代码示例

<!-- HTML 结构 -->
<div class="scroll-wrapper">
  <div class="double-row-container">
    <div class="item">卡片1</div>
    <div class="item">卡片2</div>
    <div class="item">卡片3</div>
    <div class="item">卡片4</div>
    <!-- 按需添加更多卡片 -->
  </div>
</div>
/* CSS 样式 */
.scroll-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 16px;
}

.double-row-container {
  display: inline-flex;
  flex-wrap: wrap;
  /* 固定容器高度为2行卡片总高度,避免自动折成更多行 */
  height: calc(80px * 2 + 12px); /* 计算规则:卡片高度*2 + 行间距 */
  flex-direction: column;
  gap: 12px;
}

.item {
  width: 120px;
  height: 80px;
  background: #f5f5f5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

可选优化

如果需要隐藏滚动条获得更简洁的UI,可给滚动容器添加以下样式:

/* Chrome、Safari 浏览器隐藏滚动条 */
.double-row-scroll::-webkit-scrollbar,
.scroll-wrapper::-webkit-scrollbar {
  display: none;
}
/* Firefox 浏览器隐藏滚动条 */
.double-row-scroll,
.scroll-wrapper {
  scrollbar-width: none;
}
/* IE、Edge 浏览器隐藏滚动条 */
.double-row-scroll,
.scroll-wrapper {
  -ms-overflow-style: none;
}

内容的提问来源于stack exchange,提问作者Nabin Dhakal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:15:05