'Flutter - how to set the cros axis count to dynamic in gridview flutter?

What I want to achieve is to dynamically change the crosAxisCount in gridview and set it according to the width of the widget.

I mean according to width of the widgets inside the gridview. If the widgets are long and only two can fit in the row then crosAxisCount = 2, if the widgets are small and four can fit in a row than crosAxisCount = 4.



Solution 1:[1]

//// You should use staggered grid view. By using that you can achive what you want. Just refer below dart plugin https://pub.dev/packages/flutter_staggered_grid_view

    new StaggeredGridView.countBuilder(
        crossAxisCount: , //as per your requirement
        itemCount: , //as per your requirement
        itemBuilder: (BuildContext context, int index) {
          if (index % 2 == 0) { //for even row
            return; //your required widget 
          } else { //for odd row
            return; //your required widget 
          }
        },
        staggeredTileBuilder: (int index) => index % 2 == 0
            ? new StaggeredTile.fit(2)
            : new StaggeredTile.fit(1),
      )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vishal_VE