The LayoutBuilder widget in Flutter is used to build widgets based on the parent widget's constraints. It allows you to create a widget that adjusts its layout based on the available space in its parent widget.
Attributes:
builder (Widget Function(BuildContext, BoxConstraints)):
- A builder function that returns a widget tree based on the parent widget's constraints. It takes two arguments: the BuildContext and the BoxConstraints representing the constraints of the parent widget.
Example:
import 'package:flutter/material.dart';
class LayoutBuilderExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('LayoutBuilder Widget Example'),
),
body: Center(
child: LayoutBuilder(
builder: (context, constraints) {
return Container(
width: constraints.maxWidth * 0.8,
height: constraints.maxHeight * 0.5,
color: Colors.blue,
child: Center(
child: Text(
'Width: ${constraints.maxWidth}\nHeight: ${constraints.maxHeight}',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
),
);
},
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: LayoutBuilderExample(),
));
}
Explanation:
In this example, a LayoutBuilder widget is used to build a container based on the constraints of its parent widget.
Inside the builder function, the constraints argument provides information about the available space in the parent widget.
The width and height of the container are set to 80% and 50% of the maximum width and height of the parent widget, respectively.
The container's color is set to blue, and it contains a text widget displaying the maximum width and height of the parent widget.
As the parent widget's size changes, the container adjusts its size accordingly based on the provided constraints.
This example demonstrates how the LayoutBuilder widget can be used to create responsive layouts that adapt to the available space in the parent widget.