dart - flutter : Get Local position of Gesture Det

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

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 小部件之外。为了获得本地职位,我有什么遗漏的吗?

最佳答案

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

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

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

如果您使用的是整体小部件的上下文,那么实际上您所做的是计算整体小部件内的偏移量。即

YourWidget <-- context
  Center
   Container
     GestureDetector
     ...

假设屏幕看起来像这样:

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

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

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

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

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

关于dart - flutter : Get Local position of Gesture Detector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52000130/

相关文章:

dart - 是否可以使用 Flutter 提供的 Dart SDK 作为 AngularDart

dart - 没有 AppBar 的 Flutter 应用设计

android - Flutter 使用 ProGuard 和 Firebase Auth 构建崩溃

flutter - Flutter中的Material和MaterialApp有什么区别?

firebase - flutter/Dart 错误 : The argument type 'Fu

dart - 在 Flutter 中使用 JS 库

android - 如何在 Flutter 中的图像上显示文本?

firebase - Flutter Admob AppID 使用 Android 还是 iOS?

flutter - 如何停止 flutter 应用程序中的firebase错误

flutter - Flutter 如何处理方向变化