0

I'm confuse about the usage of gridview in flutter. I want to display a list of features with their rates. The feature component/widget isn't that big in term of height but when I place them in a gridview the height of each case is way more bigger that it needs to be.

enter image description here

How can I control the height of each case to fit the child height ?

here is my code :

import 'package:flutter/material.dart';
import 'package:project/Components/ReviewComps/AttributeRatings.dart';
    
class ReviewPage extends StatelessWidget {
      const ReviewPage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: SingleChildScrollView(
          child: Container(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: const <Widget>[
                AttributeRatings(),
              ],
            ),
          ),
        ));
      }
    }

here is my gridview that create problems :

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    var featureList = [
      _featureItems(4),
      _featureItems(3.2),
      _featureItems(1),
    ];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text("Features average rating"),
        GridView.count(
          crossAxisCount: 2,
          crossAxisSpacing: 20,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          children: featureList,
        ),
      ],
    );
  }
}

Container _featureItems(double rate) {
  return Container(
    color: Colors.red,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Feature'),
            Text(rate.toString()),
          ],
        ),
        Stack(
          children: [
            Container(
              height: 2,
              width: double.infinity,
              color: const Color(0xffDBDFED),
            ),
            FractionallySizedBox(
              widthFactor: rate / 5,
              child: Container(
                height: 2,
                color: const Color(0xff39B0EA),
              ),
            )
          ],
        )
      ],
    ),
  );
}

3 Answers3

0

You can give childAspectRatio to customise a height as following

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    var featureList = [
      _featureItems(4),
      _featureItems(3.2),
      _featureItems(1),
    ];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text("Features average rating"),
        GridView.count(
          crossAxisCount: 2,
          crossAxisSpacing: 20,
          childAspectRatio: 4,//You may have to calculate based on screen size
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          children: featureList,
        ),
      ],
    );
  }
}

Container _featureItems(double rate) {
  return Container(
    color: Colors.red,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Feature'),
            Text(rate.toString()),
          ],
        ),
        Stack(
          children: [
            Container(
              height: 2,
              width: double.infinity,
              color: const Color(0xffDBDFED),
            ),
            FractionallySizedBox(
              widthFactor: rate / 5,
              child: Container(
                height: 2,
                color: const Color(0xff39B0EA),
              ),
            )
          ],
        )
      ],
    ),
  );
}
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17
  • Yeah I tried that solution but my textstyle might change so the aspect ration might break if the font size is too big. – L'homme Sage Feb 15 '23 at 04:07
0

The solution I found is quite complicated but I changed the gridview to a list view and put rows inside. The most dificult was to work with odd lengths lists here is my solution :

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    var featureList = [4, 3.2, 4, 2, 3.2];
    double nbRows = featureList.length % 2 == 0
        ? (featureList.length / 2)
        : (featureList.length / 2) + 1;
    var reworkedFeatureList = [];
    if (featureList.length % 2 == 0) {
      for (var i = 0; i < (featureList.length - 1) / 2; i++) {
        reworkedFeatureList.add([featureList[i * 2], featureList[(i * 2) + 1]]);
      }
    } else {
      final retVal = featureList.removeLast();
      for (var i = 0; i < (featureList.length - 1) / 2; i++) {
        reworkedFeatureList.add([featureList[i * 2], featureList[(i * 2) + 1]]);
      }
      reworkedFeatureList.add([retVal, -1]);
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text("Features average rating"),
        ListView.separated(
          separatorBuilder: (context, index) {
            return const SizedBox(height: 12);
          },
          itemCount: nbRows.toInt(),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) =>
              _featureItemsRow(reworkedFeatureList[index]),
        ),
      ],
    );
  }
}

Row _featureItemsRow(var rates) {
  return Row(
    children: [
      Expanded(
          child: Padding(
        padding: const EdgeInsets.only(right: 10.0),
        child: _featureItem(rates[0].toDouble()),
      )),
      Expanded(
          child: Padding(
        padding: const EdgeInsets.only(left: 10.0),
        child: _featureItem(rates[1].toDouble()),
      )),
    ],
  );
}

Column _featureItem(double rate) {
  if (rate == -1) {
    return Column();
  } else {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Feature'),
            Text(rate.toString()),
          ],
        ),
        Stack(
          children: [
            Container(
              height: 2,
              width: double.infinity,
              color: const Color(0xffDBDFED),
            ),
            FractionallySizedBox(
              widthFactor: rate / 5,
              child: Container(
                height: 2,
                color: const Color(0xff39B0EA),
              ),
            )
          ],
        )
      ],
    );
  }
}
0

I had a similar issue, where I had a GridView.builder inside a SingleChildScrollView. Now the problem is you can't create a GridView inside SingleChildScrollView because both will try to take as much space available which here makes height unbounded/infinte.

So the solution is to wrap the GridView with a SizedBox and I always prefer to use GridView.Builder.

Now the actual question, "How do I know the size of SizedBox when the list is dynamic ?"

So I wrote this code with a logic to calculate the height of SizedBox dynamically based on the childAspectRatio attribute of GridView

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(title: 'Dynamic GridView', home: Home());
  }
}

class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    final double width = MediaQuery.of(context).size.width;
    final double height = MediaQuery.of(context).size.height;
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            itemGrid(width),
          ],
        ),
      ),
    );
  }

  Widget itemGrid(double width) {
    const int count = 16;
    const int itemsPerRow = 2;
    const double ratio = 1 / 1;
    const double horizontalPadding = 0;
    final double calcHeight = ((width / itemsPerRow) - (horizontalPadding)) *
        (count / itemsPerRow).ceil() *
        (1 / ratio);
    return SizedBox(
      width: width,
      height: calcHeight,
      child: GridView.builder(
        padding: const EdgeInsets.symmetric(horizontal: horizontalPadding),
        itemCount: count,
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            mainAxisSpacing: 0,
            crossAxisSpacing: 0,
            crossAxisCount: itemsPerRow,
            childAspectRatio: ratio),
        itemBuilder: (context, index) {
          return SizedBox(
            child: Card(
              clipBehavior: Clip.hardEdge,
              child: Column(
                children: [
                  Expanded(
                      child: Image.network(
                          "https://picsum.photos/200?${DateTime.now().millisecondsSinceEpoch.toString()}")),
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 4.0),
                    child: Text(
                      "Lorem Ipsum is a dummy text, lorem ipsum",
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                      style:
                          TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
                      textAlign: TextAlign.start,
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

Link to working Dart gist - https://dartpad.dev/?id=05ba8804b19a2978a087c68622000a01

Explanation

  • count is the total number of items or itemCount.
  • itemsPerRow is the number of items in a row or crossAxisCount.
  • ratio is the childAspectRatio attribute of GridView that usually is used to set size of an item inside grid. ratio is calculated as width/height.
  • horizontalPadding is the horizontal padding given to GridView(in case of vertical list)
  • calcHeight is the calculated height of the SizedBox just so you don't need to give a fixed height in case of dynamic lists.
starball
  • 20,030
  • 7
  • 43
  • 238
Rishabh Sehgal
  • 45
  • 2
  • 11