How can I layout widgets based on the size of the parent?
Put the widget in a container and set its width and/or height to double.maxFinite
Example:
child: Container(
width: double.maxFinite,
)
you can try the IntrinsicHeight widget:
https://api.flutter.dev/flutter/widgets/IntrinsicHeight-class.html
for me this was the simplest solution. But it seems to be expensive, so you should avoid it when possible
var container = Container(
height: 200.0, // Imagine this might change
width: 200.0, // Imagine this might change
child: IntrinsicHeight(
child: Container()),
);
So I had an interesting situation where my parent child was increasing size dynamically based on the content (Text containing description). This parent widget was displaying content in read only mode but this solution might resolve other problems as well where you increase textfield height dynamically.
I had a height variable
and GlobalKey
. In initState
of widget I am using SchedulerBinding
which runs it's addPostFrameCallback
after layout is build.
The globalKey is assigned to any parent widget whose height we need for it's children.
double height = 0.0;
GlobalKey _globalKey = GlobalKey();
@override
void initState() {
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
height = _globalKey.currentContext.size.height;
print('the new height is $height');
setState(() {});
});
super.initState();
}
and rest code looks like this
// this parent having dynamic height based on content
Container(
width: 100.0,
key: _globalKey,
child: Container(
width: 100.0,
child: Row(children: [ /// you can have column as well or any other widget.
Container(child: ...),
Container(height: height,), ///this widget will take height from parent
],),
)
)
You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.
The LayoutBuilder
takes in a build()
function which has the the standard BuildContext along with the BoxConstraints as parameters that can be used to help dynamically render widgets based on size.
Let's build a simple example of widget that renders "LARGE" if the parent width is greater than 200px and "SMALL" if the parent width is less or equal to that.
var container = new Container(
// Toggling width from 100 to 300 will change what is rendered
// in the child container
width: 100.0,
// width: 300.0
child: new LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if(constraints.maxWidth > 200.0) {
return new Text('BIG');
} else {
return new Text('SMALL');
}
}
),
);