首页 > 解决方案 > flutter :获取手势检测器的本地位置

问题描述

我无法使用平移更新在手势检测器小部件上获得真实的本地位置。

new Center(    
  child new Container(
       height: 150.0,
       width: 150.0,
       decoration: new BoxDecoration(
         borderRadius: new BorderRadius.circular(5.0),
         color: Colors.white,
      ),
      child: new GestureDetector(
      onPanUpdate: (details) => onPanUpdate(context, details),
      child: new CustomPaint(
         painter: new MyPainter(
             points: points,
             limitBottom:height - 125.0,
             limitTop: 10.0,
             limitLeft: 5.0,
             limitRight: width - 55.0
         ),
       ),
    ),
  ),  
)

当我打印全局位置的偏移量 && 本地位置时,我对它们都有相同的值。结果它被绘制在我的 Container 小部件之外。为了获得当地职位,我有什么遗漏吗?

标签: dartflutter

解决方案


我假设您正在使用这样的东西来获取本地位置:

RenderBox getBox = context.findRenderObject();
var local = getBox.globalToLocal(start.globalPosition);

这样做后您得到错误偏移量的原因与context您用来查找本地位置的原因有关。

如果您正在使用整个小部件的上下文,那么基本上您所做的是计算整个小部件内的偏移量。IE

YourWidget <-- context
  Center
   Container
     GestureDetector
     ...

假设屏幕看起来像这样:

1__________________________   
|                          |  <--- YourWidget
|       2_________         |
|       | gesture |        |
|       | detector|        |
|       |   3.    |        |
|       |_________|        |
|                          |
|__________________________|

1 是整个小部件(和屏幕)的左上角,2 是手势检测器的左上角,3 是您点击的点。

通过使用 YourWidget 的上下文,您可以根据 1 和 3 之间的差异来计算点击的位置。如果 1 恰好在屏幕的左上角,则结果将匹配全局坐标。

通过使用手势检测器的上下文,您将改为测量 2 和 3 之间的距离,这将为您提供所需的偏移量。

有两种方法可以解决此问题 - 您可以将 GestureDetector 包装在Builder小部件中,或者您可以创建一个仅封装 GestureDetector 的新有状态/无状态小部件。我个人建议创建一个新的小部件。


推荐阅读