32

Trying to use an API to build the grid. Everything renders fine but after the last row of tiles the page goes blank & just keeps scrolling & scrolling &... the grid is built like so:

body: new GridView.builder(
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: (orientation == Orientation.portrait) ? 2 : 3),
      itemBuilder: (BuildContext context, int index) {
        return new Card(
          child: new GridTile(
            footer: new Text(data[index]['name']),
              child: new Text(data[index]['image']), //just for testing, will fill with image later
          ),
        );
      },
  )

The exception as I continually scroll further down the blank page with the last number (inclusive: 24) getting larger by multiples of 2 (24,26,28,etc).

I/flutter (11001): Another exception was thrown: RangeError (index): Invalid value: Not in range 0..23, inclusive: 24

Anyone seen this behavior with GridView.builder?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
JC23
  • 1,248
  • 4
  • 18
  • 28

1 Answers1

91

You can pass the item count to the builder.

Example:

body: GridView.builder(
  itemCount: data.length,
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: (orientation == Orientation.portrait) ? 2 : 3),
  itemBuilder: (BuildContext context, int index) {
    return new Card(
      child: new GridTile(
        footer: new Text(data[index]['name']),
        child: new Text(data[index]
            ['image']), //just for testing, will fill with image later
      ),
    );
  },
),

Where final orientation = MediaQuery.of(context).orientation;

Hope that helped!

Hemanth Raj
  • 32,555
  • 10
  • 92
  • 82
  • How to give portrait and landscape orientation in gridview builder.i want to give both orientation for my gridview – Vishali Feb 12 '19 at 09:24
  • 2
    Actually, wrap the `Gridview` inside a `OrientationBuilder`, which gives the current orientation. – Hemanth Raj Feb 12 '19 at 12:31
  • how can I set the fixed height of the container inside the gridView.build not depending on childAspectRatio? – Zeeshan Ansari Jan 27 '20 at 06:29
  • For orientation, use this ````crossAxisCount: (MediaQuery.of(context).orientation == Orientation.landscape) ? 4 : 1,```` – Arijeet Jul 28 '21 at 04:50