首页 > 解决方案 > 如何根据触摸坐标对齐小部件的子位置关于这个小部件?

问题描述

我有一个卡片小部件列表,我希望在用户触摸这张确切的卡片时出现一些孩子,并将其与触摸点坐标相应地对齐,例如 centerRight、topRight、bottomRight。

我怎样才能做到这一点?这是一些伪代码来说明我的问题。

        var position = Alignment.bottomRight;

        InkWell(
          onTap: (){
            /// get touch point regards first container
            /// if touched in 1/3 of child's height, then position == Alignment.topRight, and so on
          },
          child: Container(
            height: 100, width: 100,
            child: Container(
              alignment: position,
            ),
          ),
        )

标签: flutterflutter-layout

解决方案


试试这个并根据您的要求进行修改!

Alignment position = Alignment.center;
  double w = 0, h = 0, currentX = 0, currentY = 0;

  @override
  Widget build(BuildContext context) {
    w = context.size.width;
    h = context.size.height;

    return Scaffold(
        backgroundColor: Colors.white,
        body: Container(
          alignment: position,
          width: double.infinity,
          height: double.infinity,
          child: GestureDetector(
            onTapUp: (det) {
              print(det.localPosition);
              setState(() {
                currentX = det.localPosition.dx;
                currentY = det.localPosition.dy;
                if (currentX <= (w / 2) && currentY <= (h / 2))
                  position = Alignment.topLeft;
                else if (currentX < (w / 2) && currentY > (h / 2))
                  position = Alignment.bottomLeft;
                else if (currentX > (w / 2) && currentY <= (h / 2))
                  position = Alignment.topRight;
                else if (currentX > (w / 2) && currentY > (h / 2))
                  position = Alignment.bottomRight;
                //and so on... centerLeft,centerRight, etc..
              });
            },
            child: Container(
              color: Colors.green,
              width: 150,
              height: 150,
            ),
          ),
        ));
  }

推荐阅读