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

如何在Flutter中实现支持多选的staggered grid view交错网格视图

Flutter 错落网格UI实现方案

实现你要的这种高度不等的错落网格布局,最简便的方案是使用flutter_staggered_grid_view库,具体实现步骤如下:

1. 引入依赖

在项目的pubspec.yaml文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_staggered_grid_view: ^0.7.0

添加完成后执行flutter pub get完成依赖安装。

2. 核心代码实现

以下是可直接运行的示例代码,你可以根据实际需求调整卡片样式、列数、间距等参数:

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class CustomStaggeredGrid extends StatelessWidget {
  CustomStaggeredGrid({super.key});

  // 模拟卡片数据,可替换为你的实际业务数据
  final List<Widget> cardList = [
    _demoCard(height: 180, color: Colors.pinkAccent.shade100, text: "卡片1"),
    _demoCard(height: 240, color: Colors.blueAccent.shade100, text: "卡片2"),
    _demoCard(height: 150, color: Colors.greenAccent.shade100, text: "卡片3"),
    _demoCard(height: 210, color: Colors.orangeAccent.shade100, text: "卡片4"),
    _demoCard(height: 170, color: Colors.purpleAccent.shade100, text: "卡片5"),
    _demoCard(height: 220, color: Colors.yellowAccent.shade100, text: "卡片6"),
    _demoCard(height: 160, color: Colors.tealAccent.shade100, text: "卡片7"),
    _demoCard(height: 190, color: Colors.redAccent.shade100, text: "卡片8"),
  ];

  // 通用示例卡片组件,可替换为你的自定义卡片
  static Widget _demoCard({required double height, required Color color, required String text}) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Center(child: Text(text, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500))),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: const Text("错落网格效果"), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: MasonryGridView.count(
          crossAxisCount: 2, // 列数,可根据需求调整
          mainAxisSpacing: 10, // 垂直方向卡片间距
          crossAxisSpacing: 10, // 水平方向卡片间距
          itemCount: cardList.length,
          itemBuilder: (context, index) => cardList[index],
        ),
      ),
    );
  }
}

补充说明

  • 如果你的卡片高度是由内容动态决定的,不需要手动指定Container的height参数,直接传入你的自定义卡片组件即可,MasonryGridView会自动适配每个卡片的高度
  • 如果不想引入第三方库,也可以通过自定义SliverChildDelegate对原生GridView进行改造,但实现成本较高,更推荐上述第三方库方案

内容的提问来源于stack exchange,提问作者Mrunal Joshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:45:07