What are constraints in flutter

When you plan to learn Flutter, it starts with Layout. Right? Now, you cannot learn or understand flutter layout without understanding constraints. Therefore, our flutter learning starts by answering this question first – what are constraints in flutter?

Firstly, let me warn you at the very beginning. Flutter layout is not like HTML layout.

Secondly, if you come from HTML or web development background, don’t try to apply those CSS rules here. Why so? Because, HTML targets a large screen. Whereas, we’re dealing with a Mobile screen. So, layout should not be same. And, there are other reasons too.

Finally, flutter is all about widgets. As a result, we need to understand Flutter layout keeping widgets in our mind.

Let’s start with a Material App, and, start building a simple Container widget with a Text widget as its child.

import 'package:flutter/material.dart';

class ConstraintSample extends StatelessWidget {
  const ConstraintSample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Constraint Sample',
      debugShowCheckedModeBanner: false,
      home: ConstraintSampleHomme(),
    );
  }
}
@override
  Widget build(BuildContext context) {    
    return Container(
      width: 150,
      height: 200,      
      child: const Text('Constraint Sample'),      
    );
  }

Let’s run this simple flutter app, and see what happens.

Constraint in flutter example one
Constraint in flutter example one

What is the problem here?

We’ve returned a Container widget mentioning its width and height.

return Container(
      width: 150,
      height: 200,      
      child: const Text('Constraint Sample'),      
    );

However, that didn’t work at all.

Now we know that the constraint in Flutter is all about the size of the box, which is nothing but a widget.

A size always deals with width and height.

In the above case, the material app takes the width and height of the whole screen and directs its immediate child Container to take that size.

That is why, although we’ve mentioned the size of the Container widget, it doesn’t work.

Therefore, we can conclude that any Widget gets its constraint or size from its immediate parent. After that, it passes that constraint to its immediate child.

And this practice goes on as the number of Widgets increases in the widget tree.

In Flutter, a parent widget always controls the immediate child’s size. However, when the parent becomes grand-parent, it cannot affect the constraint or size of the grand-child.

Why?

Because, the grand child has its parent that inherits the size from its parent and decides what should be the size of its child.

We can compare this mechanism with wealth. If a person inherits some wealth from her parent, she is in a position to decide how much of that wealth she will give to her child or children.

And this process goes on.

One after another widget tells its children what their constraints or sizes are.

How do you use constraints in flutter?

Since we have got the idea, now we can apply and see how we can use constraints in flutter.

Our next code snippet is like the following.

@override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 100,
        color: Colors.amber,
        alignment: Alignment.bottomCenter,        
        child: const Text(
          'Constraint Sample',
          style: TextStyle(
            fontSize: 25,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        
      ),
    );
  }

Now, we’ve wrapped the Container widget with a Center widget. As a result, the Center widget gets the full size now. And, after that, it asks immediate child Container widget how big it wants to be.

The Container said, “I want to be 300 in width and 100 in height. Not only that, I want to place my child at the bottom Center position. And, I also want my child should be of color amber.”

The Center widget says, “Okay. No problem. Get what you want because I have inherited the whole screen-size from my parent. Take what you need.”

As a result, we see this on the screen.

Constraint in flutter example three
Constraint in flutter example two

Next, we change our code to this:

@override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 100,
        color: Colors.amber,
        alignment: Alignment.bottomCenter,
        child: Container(
          width: 200,
          height: 50,
          color: Colors.blue,
          alignment: Alignment.center,
          child: const Text(
            'Constraint Sample',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

Let’s see the effect on the screen first. Then we’ll discuss the code.

Constraint in flutter example four
Constraint in flutter example three

The above image is displayed because the code says that the child Container with width 300, height 100 and color amber has a child, which is another Container and that has color blue, width 200 and height 50. However, the parent Container decides that it will show its child in the bottom Center position.

Align the child at the bottom Center means, we would pass this child Container a tight constraint that is bigger than the child’s natural size, with an alignment of Alignment.bottomCenter.

As a result, the child Container gets the width 200 and height 50 and is placed at the bottom Center alignment. It happens smoothly because the parent Container’s width and height is bigger than the child Container. Therefore, it allocates the exact size that it’s asked for.

But it didn’t happen, if the parent Container didn’t set the alignment and said that, “Okay, child container, you can place yourself anywhere you like. Even you may decide your alignment.”

So the code is like the following:

 @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 100,
        color: Colors.amber,
        child: Container(
          width: 200,
          height: 50,
          color: Colors.blue,
          alignment: Alignment.center,
          child: const Text(
            'Constraint Sample',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

As a result, the child Container decides to looks upward and tries to find if its grand-parent has any alignment already allocated for it.

While looking upward, it finds that the grand-parent is a Center widget itself. Therefore, it decides to take the Center position, as it has the Center alignment itself; and not only that, while doing so, it ignores its own width and height, and it takes the width and height of the immediate parent, which eventually is another Container.

As a result it overlaps completely the parent Container.

To sum up, constraints are basically sizes of width and height that any Widget gets from its parent. However, in case, padding is added, the constraint may change. Although we have not added that feature, still you may test that on your own and see how it affects the sizes of the child.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

7 responses to “What are constraints in flutter”

  1. […] the previous section we have discussed what constraints are. In Flutter, every widget is rendered by their underlying RenderBox objects. As a result, for […]

  2. […] on the mobile, tab or desktop screen. Consequently, since each box has a size, every widget has constraints that deal with width and […]

  3. […] to the layout model, the invisible widgets use constraint, align, aspect ratio, baseline and other Widgets to arrange visible widgets […]

  4. […] to the layout model, the invisible widgets use constraint, align, aspect ratio, baseline and other Widgets to arrange visible widgets […]

  5. […] Secondly, the SimpleDialog Widget has an optional title that positions itself above the choices. […]

  6. […] Deuxièmement, le widget SimpleDialog a un titre facultatif qui se positionne au-dessus des choix. […]

  7. […] Deuxièmement, le widget SimpleDialog a un titre facultatif qui se positionne au-dessus des choix. […]

Leave a Reply