Home > OS >  Setting container width automatically in flutter
Setting container width automatically in flutter

Time:09-13

I am loading data from Api. So I need to set it inside a container. So I can't set a fixed width. The width should change automatically or expand according to the length of data. Is there any way to do this?

CodePudding user response:

Wrap your container with the Expanded widget.

CodePudding user response:

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")
    ),

)

CodePudding user response:

Just one add to Mansoor's answer Malik you can assign a minWidth in constraints. To make the container appear even if there is no text inside it

  • Related