用百分比在堆栈中定位小部件

Rém*_*let 9 dart flutter

假设我想在 a 内放置一个小部件,Stack但使用堆栈位置的百分比而不是固定大小。如何在颤振中做到这一点?

我希望Positionned.fromRelativeRect构造函数就是这样,使用介于 0 和 1 之间的浮点数。但似乎没有。

Align允许以百分比定位小部件。但是heightFactorwidthFactor更改Align大小而不是子大小。这不是我想要的。

Rém*_*let 14

你可以结合 aPositioned.fillLayoutBuilder来达到这样的结果。

    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,),
            );
          },
        ),
      )
    ],
  ),
Run Code Online (Sandbox Code Playgroud)


小智 8

我不久前发现的一件事是,您可以在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), 

Run Code Online (Sandbox Code Playgroud)

  • 您可以仅使用“Alignment(-1.0 + x * 2, -1.0 + y * 2)”,其中“x”和“y”分别占 x 和 y 的百分比 (5认同)

Але*_*ров 6

使用FractionalOffset&FractionallySizedBox对比起来非常简单

  • 周围没有不必要的代码,比如 Positioned.fill
  • 没有没有额外的计算,比如 Alignment
...
 Container(
   color: Colors.blue[200],
   alignment: FractionalOffset(0.7, 0.6),
   child: FractionallySizedBox(
     widthFactor: 0.1,
     heightFactor: 1/3,
     child: Container(color: Colors.red[900])
   ),
 ),
...
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明