Flutter Horizontal gridview with dynamic width

1,383

This is the max I could achieve by using ternary operator to adjust mainAxisCellCount. You can adjust the the count according to the length of you shortest and longest string.

   Container(
            height: 180.0,
            child: StaggeredGridView.countBuilder(
              crossAxisCount: 4,
              itemCount: 8,
              scrollDirection: Axis.horizontal,
              itemBuilder: (BuildContext context, int index) =>  Container(
                child: Center(child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0),
                    child: Chip(
                        label: Text('${fruits[index]}', overflow: TextOverflow.visible, maxLines: 1, style: TextStyle(),)))),
              ),
              staggeredTileBuilder: (int index) => StaggeredTile.count(2, fruits[index].length > 3 ? fruits[index].length > 8 ? fruits[index].length > 2 ? 4 : 3 : 2 : 1),
              mainAxisSpacing: 0.0,
              crossAxisSpacing: 0.0,
            ),
          ),

enter image description here

Share:
1,383
mrgnhnt96
Author by

mrgnhnt96

I love Flutter!

Updated on December 19, 2022

Comments

  • mrgnhnt96
    mrgnhnt96 over 1 year

    I have tried using Flutter_staggered_grid_view, but it seems as though that its built better for vertical scrolling.

    My goal is to have a horizontal gridview with dynamic widths to make the grid feel natural and not so spread apart

    This is what I have (I removed some of the UI code, but its essentially the same)

    GridView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: sourceList.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: .3),
      itemBuilder: (context, i) {
        final e = sourceList[i];
        return Text(
          e.name,
        );
      },
    );
    

    enter image description here

    And this is what I am looking for

    enter image description here

    • Nayef Radwi
      Nayef Radwi over 3 years
      I am not quite sure, which is why I'm commenting but can you just have the child aspect ratio as a variable and then modify it based on mediaQuery.of(context).size.width?