Google News
logo
Flutter - Interview Questions
What is a Flutter LayoutBuilder and how is it used?
In Flutter, `LayoutBuilder` is a widget that provides information about the size constraints of its parent widget. It takes a callback function as a parameter, and this function is called with a `BoxConstraints` object as an argument. The `BoxConstraints` object represents the constraints on the size and position of the child widget.

Here is an example of how `LayoutBuilder` can be used :
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('LayoutBuilder')),
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.blue,
          child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return Container(
                width: constraints.maxWidth * 0.5,
                height: constraints.maxHeight * 0.5,
                color: Colors.red,
              );
            },
          ),
        ),
      ),
    );
  }
}

In this example, `LayoutBuilder` is used to get the maximum width and height of the parent `Container` widget, and then use this information to size and position a child `Container` widget. The child `Container` widget is half the width and half the height of the parent `Container`, and is colored red to make it visible.

Advertisement