Search code examples
flutterdartgridviewhorizontal-scrollinghorizontalscrollview

Flutter Horizontal gridview with dynamic width


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


Solution

  • 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