LayoutBuilder
provide constrains based on its parent widget. You can wrap LayoutBuilder
with a SizedBox, then check the constraints of it.
But for the MediaQuery.of(context).size
it will provide the screen size, doesnt matter it is wraped with a SizedBox or not.
- To get screen size inside widget tree, you can use
MediaQuery.of(context).size
,The size of the media in logical pixels (e.g, the size of the screen).
- To get parent widget size, and layout inner children based on parent, use
LayouBuilder
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
SizedBox(
width: 100,
height: 100,
child: LayoutBuilder(
builder: (context, constraints) {
return Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
color: Colors.red.withOpacity(.3),
alignment: Alignment.center,
child: Text("Using layout Builder"),
);
},
),
),
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.green.withOpacity(.3),
alignment: Alignment.center,
child: Text("Using MediaQuery"),
)
],
));
}
}
For size, you can use LayoutBuilder while the competent will be based on parent widget and it doesn't call the query. Somecases like on showDialog you need mediaQuery to get size. Use LayoutBuilder
whenever possible.
More about LayoutBuilder
and MediaQueryData/size