Rahul Kavati
Rahul Kavati

Reputation: 4080

How to build gridview with custom width in Flutter?

Based on the child width grid view should be built.

Upvotes: 1

Views: 1277

Answers (2)

retour
retour

Reputation: 571

You can also consider using a SliverGrid with SliverGridDelegateWithMaxCrossAxisExtent.

  • You can change the maxCrossAxisExtent to give the max width of each child.
  • Then you can also change childAspectRatio to specify the height in relation to the width. (eg. childAspectRatio = 4.0 means 1/4 units tall for every unit in wide)

Below is an example from the Flutter Docs. Also here's the example on a DartPad.

SliverGrid(
  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 200.0,
    mainAxisSpacing: 10.0,
    crossAxisSpacing: 10.0,
    childAspectRatio: 4.0,
  ),
  delegate: SliverChildBuilderDelegate(
    (BuildContext context, int index) {
      return Container(
        alignment: Alignment.center,
        color: Colors.teal[100 * (index % 9)],
        child: Text('grid item $index'),
      );
    },
    childCount: 20,
  ),
)

Upvotes: 0

Siloé Bezerra Bispo
Siloé Bezerra Bispo

Reputation: 2244

If you don't care about how much items can have in a row, you can use the Wrap , it's really simple.

A example from docs, you can use a list too.

Wrap(
  spacing: 8.0, // gap between adjacent chips
  runSpacing: 4.0, // gap between lines
  children: <Widget>[
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: Text('AH')),
      label: Text('Hamilton'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: Text('ML')),
      label: Text('Lafayette'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: Text('HM')),
      label: Text('Mulligan'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: Text('JL')),
      label: Text('Laurens'),
    ),
  ],
)

Upvotes: 4

Related Questions