Reputation: 318
Stack(
children: [
Positioned(
left: ??? + 20,
child: Text('This text is 20 pixel left to the center of the stack'),
),
],
),
I am trying to position widget inside Stack relative to center.
How to get ???
in the above code?
Upvotes: 5
Views: 5739
Reputation: 16300
You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.
Try something like
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
double _constIconSize = 50;
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
print(constraints);
return Stack(
children: <Widget>[
//Exact center
Positioned(
top: constraints.constrainHeight() / 2 - _constIconSize / 2,
left: constraints.constrainWidth() / 2 - _constIconSize / 2,
child: Icon(
Icons.gps_fixed,
color: Colors.green,
size: _constIconSize,
),
),
//100 right and 50 bottom from center
Positioned(
top: constraints.constrainHeight() / 2 + 100,
left: constraints.constrainWidth() / 2 + 50,
child: Icon(
Icons.face,
color: Colors.red,
size: _constIconSize,
),
),
],
);
},
),
);
}
}
Upvotes: 8
Reputation: 4392
Here is one way of doing it
Positioned(
left: MediaQuery.of(context).size.width / 2 + 20,
child:
Text('This text is 20 pixel left to the center of the stack'),
),
Upvotes: 4