Reputation: 17882
I have a GridView widget nested inside of a SizedBox widget nested inside of a Container widget
Container(
padding: EdgeInsets.all(10),
alignment: Alignment(0, 0),
child: SizedBox(
width: min(MediaQuery.of(context).size.width,
MediaQuery.of(context).size.height) -
20,
height: min(MediaQuery.of(context).size.width,
MediaQuery.of(context).size.height) -
20,
child: GridView.count(
padding: EdgeInsets.all(0),
crossAxisCount: sqrt(tiles.length).round(),
mainAxisSpacing: 5,
crossAxisSpacing: 5,
children: tiles,
shrinkWrap: true,
),
),
),
The Container Widget has an edge inset of 10, so in the SizedBox I want the width and height to be the min screen width/height minus this edge inset (so minus 20 since it's on each side).
How can I read values of a parent widget so that I can know it's edgeInset? Can a MediaQuery accomplish this through the context?
I know that I can just store the edge inset as a variable earlier on and use that in both places, but as I am trying to learn Flutter I am more curious if there is a way to read the values/properties of parent widgets so that their children can reference them on the fly.
Upvotes: 0
Views: 2816
Reputation: 6181
Container
has a somewhat complicated behaviour so the answer to your question would depend on who the parent of the container
is.
From the documentation:
Container tries, in order: to honor alignment, to size itself to the child, to honor the width, height, and constraints, to expand to fit the parent, to be as small as possible.
For example: If you place your container in the body
paramenter of a Scaffold
and remove the SizedBox
then GridView
will fill the screen and will have the padding you specified. (In which case you don't even need Container
and you can just use Padding
widget instead.)
More broadly speaking Flutter works in a different paradigm where you don't need to "know" specifics of your parent as you potentialy can place any widget in any other widget.
Upvotes: 0
Reputation: 36
If you provide some Widget a global key
final _key = GlobalKey();
Table(
key: _key,
children: _getTableRows(),
);
then you can calculate the size of the widget like this:
void _getSize(_) {
final RenderBox _boardRender = _key.currentContext.findRenderObject();
final boardSize = MediaQuery.of(_key.currentContext).size;
final boardOffset = _boardRender.localToGlobal(Offset.zero);
//print('$boardSize:$boardOffset:$cellSize');
}
You may look at https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html
Upvotes: 1