JC23
JC23

Reputation: 1328

GridView.builder creates page that scrolls endlessly

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?

Upvotes: 36

Views: 106551

Answers (1)

Hemanth Raj
Hemanth Raj

Reputation: 34769

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!

Upvotes: 96

Related Questions