1

I am having trouble to show some list of items in a grid view. The items are grouped in different sections e.g. section is car and items to be shown in grid view are car1,car2...car10. The other section is animal and so on each having their own items.

I can implement this by adding multiple gridview widgets, but I think there might be a better way to implement this with less code.

Here is an example of what I am trying to implement. enter image description here

Abu Bakar
  • 67
  • 1
  • 12

1 Answers1

1

Using SliverGrid will provide better experience in my opinion.

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

  @override
  Widget build(BuildContext context) {
    final List<String> vehicles = ["Car", 'Motor'];
    final List<String> animals = ["Cat", 'Dog'];
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(child: Text("Vehicles")),
          SliverGrid.count(
            crossAxisCount: 3,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            children: vehicles
                .map(
                  (e) => buildItem(e),
                )
                .toList(),
          ),
          SliverToBoxAdapter(child: Text("Animals")),
          SliverGrid.builder(
            //better 
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 10,
              mainAxisSpacing: 10,
            ),
            itemBuilder: (context, index) {
              return buildItem(animals[index]);
            },
            itemCount: animals.length,
          )
        ],
      ),
    );
  }

  Container buildItem(String e) {
    return Container(
        decoration: BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.circular(9),
        ),
        alignment: Alignment.center,
        child: Text(e));
  }
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Thank you for the solution, As I have lots of sections my code will be much bigger. Main purpose of the question was to use minimal code and as you can see, I have to use SliverToBoxAdapter for every section. I have found one solution and I will give it a try https://stackoverflow.com/questions/56033728/flutter-gridview-with-header – Abu Bakar Jul 16 '23 at 15:04
  • You can always split into small widget & function. You can also check sliverTools if needed pinned header – Md. Yeasin Sheikh Jul 16 '23 at 15:12