Home > Software design >  Flutter how to set a column that wrap gridview height
Flutter how to set a column that wrap gridview height

Time:03-09

i trying to make the height of column into dynamically because the more product i have i need more height for the column, down there was my code

Container(
          width: double.infinity,
          height: 1000,
          child: GridView.builder(
            physics: NeverScrollableScrollPhysics(),
            itemCount: productsList.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 22 / 30,
                mainAxisSpacing: 5,
                crossAxisSpacing: 3),
            itemBuilder: (ctx, i) {
              return ChangeNotifierProvider.value(
                value: productsList[i],
                child: FeedsProduct(),
              );
            },
          ),
        ),

how can i set the container height dynamically?

CodePudding user response:

There is a property inside GridView called : shrinkWrap, see shrinkWrap property

Here you can find simple example

class SimpleExample extends StatelessWidget {
  const SimpleExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Column(
          children: [
            GridView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: 30,
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 22 / 30,
                  mainAxisSpacing: 5,
                  crossAxisSpacing: 3),
              itemBuilder: (ctx, i) {
                return Container(
                  color: Colors.grey,
                  child: Center(
                    child: Text("Item $i"),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

You can replace Container by Expanded : https://api.flutter.dev/flutter/widgets/Expanded-class.html

CodePudding user response:

I don't know how your code works exactly but you can wrap the Expanded() widget on GridView() instead of a container:

 Expanded(
     child: GridView.builder(
        physics: NeverScrollableScrollPhysics(),
        itemCount: productsList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 22 / 30,
            mainAxisSpacing: 5,
            crossAxisSpacing: 3),
           itemBuilder: (ctx, i) {
           return ChangeNotifierProvider.value(
            value: productsList[i],
            child: FeedsProduct(),
          );
        },
      ),
);
  • Related