Ad

How Can I Have The GridView.builder Build From The Top When Placed In A Container In Flutter?

- 1 answer

When I place the GridView.builder inside a container of a certain size (so the GridView.builder only takes up this parent's size), I can't seem to get it the children to build from the top down.

Instead, there is a gap at the top before it starts building and none at the bottom. I have tried using the Align widget and the GridView.builder parameters but I can't get it to adjust this.

How can I change this so the children can build from the top down (or even center the children with equal blank space at the top and bottom)?

Here is simplified code:


import 'package:flutter/material.dart';

class GridViewExample extends StatefulWidget {
  const GridViewExample({Key? key}) : super(key: key);

  @override
  _GridViewExampleState createState() => _GridViewExampleState();
}

class _GridViewExampleState extends State<GridViewExample> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        alignment: Alignment.topCenter,
        color: Colors.blue,
        width: 200,
        height: 500,
        child: GridView.builder(
          itemCount: 50,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 5,
          ),
          itemBuilder: (context, index) => Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              color: Colors.orange,
            ),
          ),
        ),
      ),
    );
  }
}


[![GridImage][1]][1]


  [1]: https://i.stack.imgur.com/gjuRX.png
Ad

Answer

remove its default pading :

GridView.builder(
          itemCount: 50,
          //add this line ---------<
          padding: EdgeInsets.zero,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 5,
          ),
          itemBuilder: (context, index) => Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              color: Colors.orange,
            ),
          ),
        ),
Ad
source: stackoverflow.com
Ad