Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrink container to smaller child rather than expanding to fill parent

I'm creating a custom widget for a segment control.

return Padding(
  padding: const EdgeInsets.symmetric(vertical: 20.0),
  child: Container(
    decoration: BoxDecoration(border: Border.all(color: Colors.blue)),
    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: buttons,
    ),
  ),
);

I want the container to shrink to the minimum size to contain its children. However when I include the widget in a parent, it expands to fill the parent. This is visible because the border from the decoration is larger than the buttons.

How do I force the container to shrink?

like image 206
dakamojo Avatar asked Jul 05 '18 03:07

dakamojo


People also ask

Can a container have more than one child?

Container is a Single-child layout widget. But it can have multiple children by using a Multi-child layout widget as its child.

How do you reduce the width of a container in flutter?

Flutter – Change Container Border's Color & Width To change the color and width of Container's border, use its decoration property. Set decoration property with BoxDecoration() object. Set the border property of BoxDecoration() object, with required color and width as per your applications specifications.

Can a container have multiple children flutter?

Column is a layout widget in flutter which aligns its children vertically. It can have multiple child widgets.


3 Answers

To get the container not to take up the entire parent, you need to tell it where it should be placed within the parent - by default, it doesn't know where to go so it fills the parent =D.

The simplest ways of doing this are to use an Align or a Center widget. I believe you want to put it around your Container in this case, but I'm not 100% sure.

like image 162
rmtmckenzie Avatar answered Oct 22 '22 12:10

rmtmckenzie


wrapping a Container in a Row() widget makes the container shrinks to the Container's child size as mentioned here,, https://github.com/flutter/flutter/issues/4949

Row(
 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,
   children: [
     Container(
       child:button()   
     ),
   ]
),
like image 25
Rageh El Azzazy Avatar answered Oct 22 '22 12:10

Rageh El Azzazy


bit late to the party... I'm still new to flutter so go easy on me, but I think using Align or Center as the Parent and then set the Width and Height values for the Child then the parent should shrink to the child. =D

like image 33
Myles Wilson Avatar answered Oct 22 '22 12:10

Myles Wilson