Reputation: 5635
I'm wondering if in Flutter there are any good ways of imitating the iOS Xcode constraint where you center a view inside another (say, vertically), and supply a multiplier such that instead of being exactly centered (50% of the way down the parent view), it's positioned at 30% down, or 70% down, or whatever.
(Rather than use a fixed margin from the top of the screen, I'd like to "float" a header view down by 20% of the screen height...)
Upvotes: 0
Views: 8461
Reputation: 31
Set in container of parent view
Container(alignment: Alignment.center, ...)
Upvotes: 3
Reputation: 36373
Use FractionallySizedBox
to size a widget relative to all available space, and wrap it with a Container
or Align
to specify the alignment of it.
For example:
Container(
alignment: Alignment(0, -0.5),
child: FractionallySizedBox(
heightFactor: 0.5,
widthFactor: 0.8,
child: Container(color: Colors.blue),
),
)
This makes a blue box that's 50% of screen height and 80% of screen width, positioned at 25% down vertically.
Note, for the Alignment
class, it takes in 2 parameters, for x and y axis alignment, ranges from -1 to +1. For example, (0,0) is center, (-1, -1) is top left corner, so here (0, -0.5) centers it horizontally and lifts it up half way vertically, resulting in 25% padding from the top.
Upvotes: 0
Reputation: 5635
All my FractionallySizedBox
efforts have been unreliable, but here's a way that's proven far stabler for me - using LayoutBuilder
and SizedBox
as a spacer:
LayoutBuilder(builder: (context, constraints) => Column(
children: <Widget>[
SizedBox(height: (constraints.maxHeight - constraints.minHeight) * 0.2,),
myWidget
],
))
This way constraints
give me the ability to calculate 20% of the parent height, and apply that as a spacing using a simple SizedBox.
Upvotes: 3
Reputation: 277567
FractionallySizedBox
is enough by itself to handle such layout
FractionallySizedBox(
heightFactor: .5,
widthFactor: 1.0,
alignment: Alignment.topCenter,
child: child,
)
This will top center a widget taking helf the height of its parent and full width
Upvotes: 6
Reputation: 5635
I found one way, but I'm not sure it's the neatest yet:
For vertical proportional centering:
Embed your layout inside a Center
widget that is itself inside a FractionallySizedBox
. Provided that FractionallySizedBox
is at the top of the screen, by changing its heightFactor
you effectively change the centering position caused by the Center
widget.
new FractionallySizedBox(
heightFactor: someHeightFactor,
child: Center(
child: myChildWidget
),
);
i.e. if parentHeight
= the height of the parent widget to this FractionallySizedBox
, and parentY
= the (absolute) y origin of that parent widget, then setting heightFactor = 0.6
would center your UI child inside a region measuring 0.6 * parentHeight
, therefore with an absolute y center = parentY + 0.3 * parentHeight
.
Horizontal proportional centering would be the same but using widthFactor
on the FractionallySizedBox
.
Upvotes: 2