Code pattern when wanting to use Flutter's LayoutBuilder inside a Column

735 Views Asked by At

I have a Column with two elements A and B. A has a fixed height and B is supposed to fill the rest of the screen. Within B I want to make layout decisions based on the height of B via a LayoutBuilder().

If I using the Column()-widget normally the BoxConstraint for B is given as infinitive. Is there a good pattern for this problem that gives a finite height for B?

2

There are 2 best solutions below

1
On

Use Mediaquery

Size size = MediaQuery.of(context).size;

on Container B height: size.height - containerAFixedHeight

0
On

Wrap your LayoutBuilder() in an Expanded (or a Flexible if you don't want it expanded) widget and then you can use the maxHeight constraint of the LayoutBuilder at runtime.

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        /// Widget "A":
        Container(height: 100, color: Colors.red),

        /// Widget "B":
        Expanded(
          child: LayoutBuilder(builder: (_, ct) {
            print(" Constraints(h,w): ${ct.maxHeight}, ${ct.maxWidth}");
            return Container(color: Colors.blue);
          }),
        )
      ],
    );
  }
}

Here's a test in Chrome browser:

enter image description here

Which prints Constraints(h,w): 460, 500 to terminal. Without Expanded it prints infinity for height constraint.