Search code examples
flutterlistviewdartlayouthorizontalscrollview

height of Container is stretching in Flutter, even if i put smaller value?


I am putting height for Container equal to 40, but it gets the height of parent Container. I think the ListView.builder is stretching its children, cause if i replace that with a row of that Container(look at the code) it works as expected.

import 'package:flutter/material.dart';

class PaymentScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: SafeArea(child: Column(children: [
            Container(alignment: Alignment.center, height: 200,
              child: ListView.builder(scrollDirection: Axis.horizontal, shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) =>
                /// this Container is stretching, even it has definite height
                Container(alignment: Alignment.center, margin: EdgeInsets.all(8), padding: EdgeInsets.all(8), color: Colors.amber,
                  /// this width is not listening to me!
                  width: 40, height: 40,
                    child: Text('${index + 1}'),),
                itemCount: 31,),),],),),);
  }
}

enter image description here


Solution

  • This happens because of the nature of the container. The container will naturally try to take as much as as it can. To force it to be the size that you want it to be, you need to add a middle widget to account for the space that you don't your container to fill.

    A couple of widgets that you could use are Center, Align, Stack used with a Positioned widget. You could even use a second Container, but if you have to use the alignment property to avoid the same outcome.