简体   繁体   中英

How to adapt crossAxisCount of GridView based on its width in Flutter?

What is the best practice to adapt the number of columns (crossAxisCount) of a GridView based on its width in Flutter?

Maybe I can better explain the intended behaviour by referencing HTML:

  • I create 6 boxes (eg DIVs) with a width of 200 px (and same height) each.
  • (a) If the element surrounding these boxes has a width of 400 px, it would automatically show 2 boxes per row in 3 rows.
  • (b) If the element surrounding these boxes has a width of 700 px, it would automatically show 3 boxes per row in 2 rows.

Use Wrap. It can put renderboxes as many as fit to a row, then wrap to the next row. (formerly a comment, but it looks like the answer!)

I do this like below. You can try..

  int getItemCountPerRow(BuildContext context) {
    double minTileWidth = 200; //in your case
    double availableWidth = MediaQuery.of(context).size.width;
    
    int i = availableWidth ~/ minTileWidth;
    return i;

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM