There is a weird behavior of Stack with Fittedbox in layout?

2,299

I can't tell you the specifics of the actual algorithm that makes this happen, but I can tell you why - because you're using a FittedBox. FittedBox does all sorts of calculations to try to fit your item into the parent item, based on the constraints of the parent and of the child. It's useful for things like images which have a specific aspect ratio but otherwise no constraints on their size.

Because you have a text as the child of the FittedBox, it is probably having trouble calculating the size it can scale to - I have no idea what Text would report (and I'm ignoring the Container because it basically just delegates layout to its child if it doesn't have width & height set). Try setting it to BoxFit.cover and you'll see what happens. But why it picks that particular size I have no idea.

I would recommend removing the FittedBox unless you're using an image; it is the cause of what you're seeing.

Share:
2,299
Admin
Author by

Admin

Updated on December 05, 2022

Comments

  • Admin
    Admin over 1 year

    I follow the tutorial of card topic and to write the code of flutter gallery card example

    https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/material/cards_demo.dart

    Official card example here

    I don't know the logic with stack combine with fittedbox. Why there is a height ? I just follow the tutorial of set the margin of bottom, left and right to 16.0,16.0,16.0. If i do not have any misunderstanding, it's a margin between parent and size-box. Why would have height existing ? Is there any black magic code of that? I just want to understand the logic of that.

    My result image

     var titleImage2 = new SizedBox(
          height: 200.0,
          child: new Stack(
            children : <Widget> [
                //new Text("First element" , style: new TextStyle(color: Colors.red),),
                new Positioned(
                    //top: 0.0,
                    left : 16.0, 
                    right : 16.0, 
                    bottom: 16.0,
                    //width: 100.0,
                  child: new FittedBox(
                    fit : BoxFit.scaleDown, 
                    alignment: Alignment.topLeft,
                    child : new Container(
                      child: new Text(
                          "Hello world"
                      ),
                    )
                  ),
                )],
          ),
    ); 
    

    Summary : Why only set left ,right, bottom to margin 16.0, it will appear an existing height? I'm a newbie of flutter

    left : 16.0, 
    right : 16.0, 
    bottom: 16.0,
    

    Weird image