Stack(
children: [
Positioned(
left: ??? + 20,
child: Text('This text is 20 pixel left to the center of the stack'),
),
],
),
我正在尝试将小部件相对于中心放置在Stack中。
如何在上面的代码中获得???
?
答案 0 :(得分:1)
这是一种实现方式
Positioned(
left: MediaQuery.of(context).size.width / 2 + 20,
child:
Text('This text is 20 pixel left to the center of the stack'),
),
答案 1 :(得分:1)
您将要使用LayoutBuilder小部件,该小部件将在布局时构建并提供父小部件的约束。
尝试类似
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,
),
),
],
);
},
),
);
}
}