Jose
Jose

Reputation: 351

Flutter: Need Explanation for Why Expanded() Fixes Exception Caused By Row() Widget As A Child Of A Constrained Column() Widget

I am having a problem with embedding a Row() widget as a child of parent Column() widget who was been constrained by a ConstrainedBox(maxHeight:150) widget.

With this scenario, I am getting a 'BoxConstraints forces an infinite height.' exception.

Here is the simplified code (I am only including the build() method for brevity):

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints(maxHeight: 150),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            color: Colors.yellow,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text("Hello"),
                Text("There"),
              ],
            ),
          ),
        ],
      ),
    );
  }

I had read a previous post suggesting to use Expanded() to solve the exception so I wrapped the Container() widget above with Expanded() and that worked, but my question is WHY?

I was under the impression that Expanded() simply forces its associated child widget to occupy all of its parent's available space. But does it also get its child widget to recognize the constraints from its parent?

Another interesting aspect of this scenario is that if I wrap the Row() with Expanded() instead of Container(), it will not work and the exception will be thrown. For whatever reason, it has to be the Container().

All help greatly appreciated. I love Flutter, but I am still struggling with the nitty gritty of its layout algorithm.

/Joselito

Upvotes: 0

Views: 1045

Answers (2)

Jing Wey
Jing Wey

Reputation: 198

This is because Rows and Columns will keep expanding based on their children, for Row:- it will keep expanding horizontally and you'll usually see it overflows to the right of the screen.

For Column:- it will keep expanding vertically, and usually overflows the bottom.

By using Expanded, it will force Row and Column to expand infinitely, that is why there is an exception. It's different for container as it will follow it's parent's width and height.

https://flutter.dev/docs/development/ui/layout

Upvotes: 1

Iosif Pop
Iosif Pop

Reputation: 382

I also had a lot of issues understanding constraints in flutter until I found this article. After a while I saw that the flutter team added the article in their documentation. Check it out, it's very good.

Upvotes: 0

Related Questions