Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView containing Cards doesn't calculate height correctly

Tags:

flutter

dart

I have an app using a GridView to try and lay out some Cards. The relevant code looks a bit like this

body: new GridView.count(
  crossAxisCount: 2,
  children: [new Card(
    child: new Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        const ListTile(
          leading: const Text("0", style: const TextStyle(
              fontWeight: FontWeight.bold, fontSize: 24.0)),
          title: const Text('Some Heading'),
          subtitle: const Text('My Subtitle'),
        ),
        new ButtonTheme
            .bar( // make buttons use the appropriate styles for cards
          child: new ButtonBar(
            children: <Widget>[
              new FlatButton(
                child: const Text('CALL TO ACTION'),
                onPressed: () {
                  /* ... */
                },
              ),
            ],
          ),
        ),
      ],
    ),
  ),
  // same card repeated
  ],
),

Unfortunately, it doesn't render well:

rendered

The cards are too tall, they should end just below the "CALL TO ACTION" button. How can I fix this, and have the grid rows automatically respect the height of the contents?

like image 405
Adam Williams Avatar asked Jun 24 '17 22:06

Adam Williams


People also ask

What is Childaspectratio?

child aspect ratio is basically width/height of the grid. So let's say you want the width of each grid to be 30 and the height to be 20, you would set the aspect ratio to be 3/2.

What is SliverGridDelegateWithFixedCrossAxisCount?

SliverGridDelegateWithFixedCrossAxisCount class Null safety. Creates grid layouts with a fixed number of tiles in the cross axis. For example, if the grid is vertical, this delegate will create a layout with a fixed number of columns.

How use GridView inside column flutter?

You just need to put your GridView Widget into the Expanded Widget, for example: body: new Column( children: <Widget>[ new Expanded( child: GridView. count( // Create a grid with 2 columns. If you change the scrollDirection to // horizontal, this would produce 2 rows.


1 Answers

Your problem is that the tiles of GridView.count have a default aspect ratio of 1.0 (i.e. square), and it sounds like you want your tiles to be shorter than that.

A quick fix would be to hard code the childAspectRatio to a number you like. A more nuanced approach would be to implement a SliverGridDelegate that describes the layout you want and use GridView.custom. You could also just do a ListView of 2-element Row widgets and not use GridView at all.

like image 53
Collin Jackson Avatar answered Sep 28 '22 07:09

Collin Jackson