ConstraintBox Widget – Flutter Widget Guide By Flutter Agency

· 3 min read
ConstraintBox Widget - Flutter Widget Guide By Flutter Agency
ConstraintBox Widget - Flutter Widget Guide By Flutter Agency

What is ConstraintBox Widget?

ConstraintBox Widget you will be able to impose additional constraints on its child widgets.

For example, if you wanted a child to have a minimum height of 80.0 logical pixels, you could use const BoxConstraints(minHeight: 80.0) as the constraints.

The Default constructor of ConstraintBox Widget looks like below :

ConstrainedBox({
   Key key,
   @required BoxConstraints constraints,
   Widget child,
 });

In the Above code snippet, fields marked with @required must not be empty.

Similarly, if you wanted a child to have a maximum height of 80.0 logical pixels, you could use const BoxConstraints(maxHeight: 80.0) as the constraints. Code Snippet will look like below :

 ConstrainedBox(
        constraints: BoxConstraints.expand(height: 100),
child : // To do
 )

Constraints Property

ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: Container(
          color: Colors.orange,
          child: Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                'Box Constraint',
                style: TextStyle(color: Colors.white),
              )),
        ));

Above code will give us output like below :

Box-Constraied

BoxConstraints.expand()

ConstrainedBox(
        constraints: BoxConstraints.expand(height: 100),
        child: Container(
          color: Colors.orange,
          child: Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                'Box Constraint',
                style: TextStyle(color: Colors.white),
              )),
        ));

Above code will give us output like below :

Expand-With-Height

BoxConstraints.expand(height: 100)

Code Snippet :

ConstrainedBox(
        constraints: BoxConstraints.tight(Size(125, 100)),
        child: Container(
          color: Colors.orange,
          child: Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                'Box Constraint',
                style: TextStyle(color: Colors.white),
              )),
        ));

In the above code, we have used padding widget.We will give us output like below :

Tight

BoxConstraints.tight()

Code Snippet :

ConstrainedBox(
        constraints: BoxConstraints.loose(Size(125, 100)),
        child: Container(
          color: Colors.orange,
          child: Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                'Box Constraint',
                style: TextStyle(color: Colors.white),
              )),
        ));

Above code will give us output like below :

Loose

BoxConstraints.loose()

Thanks for reading !!!
Do let us know your suggestion to serve you better.

Leave a Reply