Flutter 中的动态网格布局

问题描述 投票:0回答:1

我想在Flutter中实现这种网格布局。这将是来自网络的动态图像。如果图像超过 5 个限制,则应显示图像数。我希望布局像第一张图片在一列中,然后每列 2 个。

enter image description here

我尝试了这段代码,但没有得到预期的布局。

Expanded(
  child: GridView.builder(
    itemCount: imageUrls.length > 5 ? 6 : imageUrls.length,
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 3, 
      mainAxisSpacing: 4,
      crossAxisSpacing: 4,
      childAspectRatio: (index == 0) ? 3 : 1,
    ),
    itemBuilder: (context, index) {
      if (index == 0) {
        
        return GridTile(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: CachedNetworkImage(
              imageUrl: imageUrls[index],
              fit: BoxFit.cover,
              placeholder: (context, url) => CircularProgressIndicator(),
              errorWidget: (context, url, error) => Icon(Icons.error),
            ),
          ),
        );
      } else if (index == 5 && imageUrls.length > 6) {
        
        return Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Center(
                child: Text(
                  "+${imageUrls.length - 6}",
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ],
        );
      } else {
        
        return ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: CachedNetworkImage(
            imageUrl: imageUrls[index],
            fit: BoxFit.cover,
            placeholder: (context, url) => CircularProgressIndicator(),
            errorWidget: (context, url, error) => Icon(Icons.error),
          ),
        );
      }
    },
  ),
),
flutter dart gridview flutter-dependencies
1个回答
0
投票

我建议使用 flutter_staggered_grid_view

这是您可以使用此软件包用于您的案例的预览:

GridView.custom(
  gridDelegate: SliverQuiltedGridDelegate(
    crossAxisCount: 4,
    mainAxisSpacing: 4,
    crossAxisSpacing: 4,
    pattern: [
      const QuiltedGridTile(1, 1),
      const QuiltedGridTile(1, 1),
      const QuiltedGridTile(2, 2),
      const QuiltedGridTile(1, 1),
      const QuiltedGridTile(1, 1),
    ],
  ),
  childrenDelegate: SliverChildBuilderDelegate(
    childCount: min(imageUrls.length, 5),
    (context, index) => Container(
      color: Colors.orange,
    ),  // Set your image here instead
  ),
),
© www.soinside.com 2019 - 2024. All rights reserved.