首页 > 解决方案 > 如何根据坐标颤动在堆栈中定位小部件

问题描述

我的问题很简单。假设我的偏移值为 (128.2, 324.9),它是堆栈中某个位置的坐标。如何将小部件定位在堆栈中以该偏移值为目标。我目前有我的GestureDetector班级给我这个坐标值,但我还想动态地在那个位置添加一个小部件。

Widget addIndicatorImage(Offset offset) {
    if(_tapPosition!=null){
      return Positioned(child:
      new Image.asset('images/pain_report_indicator.png',
        height: 32, width: 32,));
    }else{
      return Container();
    }

  }

 Stack(
                children: [
                  GestureDetector(
                    onTapDown: _handleTapDown,
                    onTap: () {

                    },
                    child: Container(
                        child: Image.asset(
                      images[index],
                      height: 500,
                      width: double.infinity,
                    )),
                  ),
                  addIndicatorImage(_tapPosition),
                  ),
                ],
              ),

标签: flutterdart

解决方案


例子

Center用于允许Stack填充它可以填充的最大空间,受其父级限制,否则会Stack尝试根据其内容调整自身大小(如果我没记错的话)。

Container之间CenterStack仅用于(复制/粘贴)插图以显示堆栈的尺寸/边框。不需要此小部件。

Positioned部件通常需要两个参数, anX和 a Y。但是,有点令人困惑的部分是它不会自动使用您孩子的左上角。相反,您可以选择您希望从Stack. 请参阅下面代码中的注释。例如,您可以使用right:andbottom:代替top:andleft:

class StackPositionedExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(width: 5, color: Colors.lightGreenAccent)
        ),
        child: Stack(
          children: [
            Positioned(
              left: 50, // distance between this child's left edge & left edge of stack
              top: 150, // distance between this child's top edge & top edge of stack
              child: Container(
                height: 100,
                width: 100,
                color: Colors.blue,
                alignment: Alignment.center,
              ),
            )
          ],
        ),
      ),
    );
  }
}

推荐阅读