Search code examples
flutterflutter-containerflutter-card

Container size depending on his content (text)


I want my container to have different size depending on their content (in this case a text), if one user write a longer text the container will be biger and if another user write a shorter text the container will be smaller.

Is it possible? And if not is there another way to do it?

Thanks

This is what I want to achieve (it's a screenshot of Samsung note app)


Solution

  • You need to not assign width or height to the Container so it will resize depending on the child:

    
    Container(
         color: Colors.red,
         child: const Text("Hi there111"),
    )
    
    

    If you want to control max width and max height you will use Container's constraints field

    
    Container(
          color: Colors.red,
          constraints: const BoxConstraints(
              maxWidth: 200,
          ),
          child: const Text("Hi there11122222222"),
    )
    
    

    And of course you can give it minWidth and minHeight in BoxConstraints.

    Result when you are under maxWidth

    enter image description here

    Result when you have text so long that it goes over the bounds of maxWidth, in this case height resizes automatically:

    enter image description here

    You can also add padding for better look:

    
    Container(
        padding: EdgeInsets.all(20),
        color: Colors.red,
        constraints: const BoxConstraints(
          maxWidth: 200,
        ),
        child: const Text("Hi there11122222222222222222"),
    )
    
    

    enter image description here

    But for other types of widgets, other than Text it will be much safer if you wrap them with FittedBox like this, notice the Text widget :

    
    Container(
        padding: EdgeInsets.all(20),
        color: Colors.red,
        constraints: const BoxConstraints(
          maxWidth: 200,
        ),
        child: FittedBox(
           fit: BoxFit.fill,
           child: const Text("asfasfasfasfasf")
        ),
    
    )