【发布时间】:2017-10-08 23:56:14
【问题描述】:
假设我想在 Stack 内放置一个小部件,但使用堆栈位置的百分比而不是固定大小。如何在颤振中做到这一点?
我希望 Positionned.fromRelativeRect 构造函数会使用 0 到 1 之间的浮点数。但似乎不是。
Align 允许以百分比定位小部件。但是heightFactor 和widthFactor 更改了Align 大小而不是子大小。这不是我想要的。
【问题讨论】:
假设我想在 Stack 内放置一个小部件,但使用堆栈位置的百分比而不是固定大小。如何在颤振中做到这一点?
我希望 Positionned.fromRelativeRect 构造函数会使用 0 到 1 之间的浮点数。但似乎不是。
Align 允许以百分比定位小部件。但是heightFactor 和widthFactor 更改了Align 大小而不是子大小。这不是我想要的。
【问题讨论】:
您可以结合Positioned.fill 和LayoutBuilder 来实现这样的结果。
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,),
);
},
),
)
],
),
【讨论】:
【讨论】:
我不久前发现的一件事是,您可以借助 Alignment.lerp(x,y,z) 函数使用容器的对齐参数在屏幕上定位小部件
//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),
【讨论】:
Alignment(-1.0 + x * 2, -1.0 + y * 2) 其中x 和y x 和y 的百分比
如果您想使用LayoutBuilder,请不要使用Positioned.fill,如下所示:
你需要一个LayoutBuilder,不需要把每个元素都转过来用Transform.translate代替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,),
),
...
],
);
}
)
【讨论】: