1

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

1 Answer 1

3

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.

1
  • 1
    Thanks. Adding an Align as a parent to the Container fixed it for me. So an Align won't stretch itself to 100%. Good to know. When adding a Container with a height of 80, most people would expect its child would be 80 high no matter what the Container's parent is. Apr 1, 2022 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.