【问题标题】:Flutter - Why onVerticalDragEnd does not work?Flutter - 为什么 onVerticalDragEnd 不起作用?
【发布时间】:2018-12-17 14:47:13
【问题描述】:

我正在尝试获取用户是否使用 GestureDetector 小部件水平或垂直滑动。出于某种原因,我无法使 onVerticalDragEnd 属性工作。 Horizo​​ntalDragEnd 工作得很好。

我应该添加什么吗?

`

child: new GestureDetector(
                  onHorizontalDragEnd: (DragEndDetails details) {
                    print("horizontal drag");
                  },
                  onVerticalDragEnd : (DragEndDetails details) {
                    print("vertical drag");
                  } ,
                  child: new GridView.count(..

`

【问题讨论】:

  • 你很可能在某个地方有另一个小部件可以捕捉到这个手势。如ListView

标签: android flutter dart flutter-widget


【解决方案1】:

早安,

这不起作用的原因是您不能同时指定onHorizontalDragonVerticalDrag。这样做会导致其中一个识别器被忽略。在这种情况下,似乎垂直手势被忽略而有利于水平。

参考:https://github.com/flutter/flutter/blob/03a1f4acb315bd5cd99c5cafe19a4875f9f98422/packages/flutter/lib/src/widgets/gesture_detector.dart#L187

希望这可以为您解决问题:)

【讨论】:

  • 如果我删除 onHorizo​​ntalDrag 它仍然不会执行垂直的。此外,如果我不使用 GridView 作为孩子,水平和垂直拖动都可以很好地工作。这是一个错误还是一个限制?
  • 它起作用的原因是因为您使用的是网格视图:P
【解决方案2】:

在创建 GestureDetector 和/或父组件时尝试记录,并查看它是否在 End 事件之前重新渲染。我遇到了同样的问题,这是由于我使用的 Update 事件的副作用导致重新渲染。在进行了一些修改以防止这种情况发生后,End 事件开始工作。

【讨论】:

    【解决方案3】:

    看起来 GridView 小部件正在捕捉垂直拖动手势。可能不是最佳解决方案,但通过将 GestureDetector 小部件作为每个 GridView 子级的父级,我能够完成这项工作。

    【讨论】:

      【解决方案4】:

      您可以使用侦听器代替 GestureDetector,它对我有用。以下是我的实现方式-

      import 'dart:math';
      
      double radians(double degree) {
          return ((degree * 180) / pi);
        }
      
      void swipe(moveEvent) {
      double angle = radians(moveEvent.delta.direction);
          if (angle >= -45 && angle <= 45) {
            print("Swipe Right");
          } else if (angle >= 45 && angle <= 135) {
            print("Swipe Down");
          } else if (angle <= -45 && angle >= -135) {
            print("Swipe Up");
          } else {
            print("Swipe Left");
          }
      }
      
      child: Listener(
        onPointerMove: (moveEvent) => swipe(moveEvent),
        child: GridView.count(...),
      )
      

      但这会在一次滑动中多次调用函数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 2022-10-01
        • 2022-08-02
        • 1970-01-01
        相关资源
        最近更新 更多