Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

listview - 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

question from:https://stackoverflow.com/questions/65938719/height-of-container-is-stretching-in-flutter-even-if-i-put-smaller-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...