Let's say I want to position a widget inside a Stack
but with a percent of the Stack position instead of a fixed size. How to do that in flutter ?
I'd expect that the Positionned.fromRelativeRect
constructor would be the thing, using floats between 0 and 1. But seems like no.
Align
allows to position the widget in percent. But heightFactor
and widthFactor
changes the Align
size instead of the child size. Which is not what I want.
That's how to get the size and position of a widget rendered on the screen. Basically, you need to get the RenderBox of the widget. Then, you can access the size property to get the size of the widget and call localToGlobal method to get the offset.
How do you set absolute position in Flutter? To specify an absolute position for a widget as x-y coordinates, nest it in a Positioned widget that is itself nested in a Stack widget. Positioned gives you access to properties like top , left , right , and bottom , similar to CSS.
You can Use Align widget and align your dialog widget as per your need. Here in example i am setting it to the bottomCenter that is Alignment(0, 1) . Example code: Align( alignment: Alignment(0, 1), child: Material( shape: RoundedRectangleBorder(borderRadius: BorderRadius.
You can combine a Positioned.fill
and LayoutBuilder
to achieve such result.
new Stack(
children: <Widget>[
new Positioned.fill(
child: new LayoutBuilder(
builder: (context, constraints) {
return new Padding(
padding: new EdgeInsets.only(top: constraints.biggest.height * .59, bottom: constraints.biggest.height * .31),
child: new Text("toto", textAlign: TextAlign.center,),
);
},
),
)
],
),
If you want to use LayoutBuilder
then do without Positioned.fill
, like this:
you need one LayoutBuilder
, no need to turn around every elements and use Transform.translate
instead of Padding
.
new LayoutBuilder(
builder: (context, constraints) {
return Stack(
children: <Widget>[
Transform.translate(
offset: Offset(
constraints.biggest.width * left,
constraints.biggest.height * top),
child: new Text("toto", textAlign: TextAlign.center,),
),
...
],
);
}
)
one thing that i figured out not long ago is that you can position a widget on the screen using a container its alignment parameter with the help of the Alignment.lerp(x,y,z)
function
//the widget will be placed in the center of the container
alignment: Alignment.lerp(Alignment.topCenter, Alignment.bottomCenter, 0),
//the widget will be placed in the bottom of the container
alignment: Alignment.lerp(Alignment.topCenter, Alignment.bottomCenter, 1),
//the widget will be placed in the bottom quarter of the container
alignment: Alignment.lerp(Alignment.topCenter, Alignment.bottomCenter, 0.5),
//the widget will be placed in the top quarter of the container
alignment: Alignment.lerp(Alignment.topCenter, Alignment.bottomCenter, -0.5),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With