如何在Flutter Grid Builder中的每10个网格后添加一个完全拉伸的黄色容器?

huangapple go评论65阅读模式
英文:

How to add a fully stretched yellow container after every 10 grids in a Flutter Grid Builder?

问题

我有一个Flutter应用程序,我正在使用Grid Builder来显示一个项目网格。在每10个网格之后,我想要插入一个完全拉伸的黄色容器来分隔各个部分。例如,第一行应包含网格1到5,第二行应包含网格6到10,然后在显示下一行的网格11到15之前应插入一个黄色容器。这个模式应持续到网格的末尾(例如,100个网格)。

我已经附上了当前的代码和一个参考图像。请您指导我如何实现这个功能?非常感谢。

GridView.builder(
  itemCount: 100,
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 5,
  ),
  itemBuilder: (BuildContext context, int index) {
    if ((index + 1) % 11 == 0) {
      // 在每第10个容器后添加黄色拉伸容器
      return Container(
        color: Colors.yellow,
        height: 50,
        width: double.infinity,
      );
    } else {
      // 常规的正方形圆角容器
      return Container(
        margin: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
        ),
        child: Center(
          child: Text('${index + 1}'),
        ),
      );
    }
  },
)

如何在Flutter Grid Builder中的每10个网格后添加一个完全拉伸的黄色容器?


<details>
<summary>英文:</summary>

I have a Flutter application where I&#39;m using a Grid Builder to display a grid of items. After every 10 grids, I want to insert a fully stretched yellow container to separate the sections. For example, the first row should contain grids 1 to 5, the second row should contain grids 6 to 10, and then a yellow container should be inserted before displaying grids 11 to 15 on the next row. This pattern should continue until the end of the grid (e.g., 100 grids).

I have attached the current code and an image for reference. Could you please guide me on how to achieve this functionality? Thank you in advance.

GridView.builder(
itemCount: 100,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5,
),
itemBuilder: (BuildContext context, int index) {
if ((index + 1) % 11 == 0) {
// Add yellow color stretch container after every 10th container
return Container(
color: Colors.yellow,
height: 50,
width: double.infinity,
);
} else {
// Regular square rounded shape container
return Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
),
child: Center(
child: Text('${index + 1}'),
),
);
}
},
)

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/chxCG.png

</details>


# 答案1
**得分**: 0

以下是代码的翻译部分:

```dart
这是一个简单的示例。

    class TestScreen extends StatelessWidget {
      const TestScreen({super.key});
    
      @override
      Widget build(BuildContext context) {
        // 您想要分隔数据的数量。
        const int splitCount = 10;
    
        // 您拥有的项目。根据您的条件进行更改。
        final List<int> items = List.generate(
          100,
          (index) => index,
        );
    
        return Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: const Text('Staggered GridView'),
          ),
          body: SafeArea(
            child: SingleChildScrollView(
              child: TestStaggerdGridView(
                items: items,
                splitCount: splitCount,
                crossAxisCount: 5,
              ),
            ),
          ),
        );
      }
    }
    
    class TestStaggerdGridView extends StatelessWidget {
      const TestStaggerdGridView({
        super.key,
        required this.items,
        required this.splitCount,
        required this.crossAxisCount,
      });
    
      /// 您拥有的项目。根据您的条件进行更改。
      final List<int> items;
    
      /// 您要分隔项目的数量。
      final int splitCount;
    
      /// 每个轴上的单元格数。
      final int crossAxisCount;
    
      @override
      Widget build(BuildContext context) {
        final int addedCount = items.length ~/ (splitCount + 1);
    
        return StaggeredGrid.count(
          axisDirection: AxisDirection.down,
          crossAxisCount: crossAxisCount,
          children: List.generate(
            items.length + addedCount,
            (index) {
              if ((index + 1) % (splitCount + 1) == 0) {
                return StaggeredGridTile.count(
                  mainAxisCellCount: 1,
                  crossAxisCellCount: crossAxisCount,
                  child: _stretchedItem(),
                );
              } else {
                int itemIndex = (index - (index ~/ (splitCount + 1)));
    
                return StaggeredGridTile.count(
                  mainAxisCellCount: 1,
                  crossAxisCellCount: 1,
                  child: _normalItem(itemIndex),
                );
              }
            },
          ),
        );
      }
    
      Widget _normalItem(int itemIndex) {
        return Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.white,
          ),
          child: Center(child: Text('${itemIndex + 1}')),
        );
      }
    
      Widget _stretchedItem() {
        return Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.yellow,
          ),
        );
      }
    }

请注意,这只是代码的翻译部分,不包括图像或其他内容。

英文:

Here's a simple example.

class TestScreen extends StatelessWidget {
  const TestScreen({super.key});

  @override
  Widget build(BuildContext context) {
    // The number you want to sperate the data.
    const int splitCount = 10;

    // Items that you have. Change this to suit your conditions.
    final List&lt;int&gt; items = List.generate(
      100,
      (index) =&gt; index,
    );

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(&#39;Staggered GridView&#39;),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: TestStaggerdGridView(
            items: items,
            splitCount: splitCount,
            crossAxisCount: 5,
          ),
        ),
      ),
    );
  }
}

class TestStaggerdGridView extends StatelessWidget {
  const TestStaggerdGridView({
    super.key,
    required this.items,
    required this.splitCount,
    required this.crossAxisCount,
  });

  /// Items that you have. Change this to suit your conditions.
  final List&lt;int&gt; items;

  /// The number you want to seprate the items.
  final int splitCount;

  /// The number of cell count in an axis.
  final int crossAxisCount;

  @override
  Widget build(BuildContext context) {
    final int addedCount = items.length ~/ (splitCount + 1);

    return StaggeredGrid.count(
      axisDirection: AxisDirection.down,
      crossAxisCount: crossAxisCount,
      children: List.generate(
        items.length + addedCount,
        (index) {
          if ((index + 1) % (splitCount + 1) == 0) {
            return StaggeredGridTile.count(
              mainAxisCellCount: 1,
              crossAxisCellCount: crossAxisCount,
              child: _stretchedItem(),
            );
          } else {
            int itemIndex = (index - (index ~/ (splitCount + 1)));

            return StaggeredGridTile.count(
              mainAxisCellCount: 1,
              crossAxisCellCount: 1,
              child: _normalItem(itemIndex),
            );
          }
        },
      ),
    );
  }

  Widget _normalItem(int itemIndex) {
    return Container(
      margin: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Center(child: Text(&#39;${itemIndex + 1}&#39;)),
    );
  }

  Widget _stretchedItem() {
    return Container(
      margin: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.yellow,
      ),
    );
  }
}

如何在Flutter Grid Builder中的每10个网格后添加一个完全拉伸的黄色容器?

答案2

得分: 0

以下是翻译好的代码部分:

这是我对此的看法... 使用 .skip  .take 用于子组:

final items = Iterable<int>.generate(47).toList();

class Body extends StatelessWidget {
  const Body({
    super.key,
  });

  @override
  Widget build(BuildContext context) => ListView.separated(
        itemBuilder: (context, index) {
          final group = items.skip(index * 10).take(10).toList();
          if (group.isEmpty) return null;
          return GridView.count(
            crossAxisCount: 5,
            shrinkWrap: true,
            children: [
              for (final item in group)
                Container(
                  margin: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Colors.blue,
                  ),
                  child: Center(
                    child: Text('$item'),
                  ),
                )
            ],
          );
        },
        separatorBuilder: (context, index) => const Divider(
          thickness: 32,
          height: 40,
          color: Colors.yellow,
        ),
        itemCount: (items.length / 10).ceil(),
      );
}
英文:

Here's my take on it... using .skip and .take for the subgroups:

final items = Iterable&lt;int&gt;.generate(47).toList();

class Body extends StatelessWidget {
  const Body({
    super.key,
  });

  @override
  Widget build(BuildContext context) =&gt; ListView.separated(
        itemBuilder: (context, index) {
          final group = items.skip(index * 10).take(10).toList();
          if (group.isEmpty) return null;
          return GridView.count(
            crossAxisCount: 5,
            shrinkWrap: true,
            children: [
              for (final item in group)
                Container(
                  margin: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Colors.blue,
                  ),
                  child: Center(
                    child: Text(&#39;$item&#39;),
                  ),
                )
            ],
          );
        },
        separatorBuilder: (context, index) =&gt; const Divider(
          thickness: 32,
          height: 40,
          color: Colors.yellow,
        ),
        itemCount: (items.length / 10).ceil(),
      );
}

huangapple
  • 本文由 发表于 2023年6月29日 21:19:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定