简体   繁体   English

在 Flutter 中检测垂直滑动方向

[英]Detect vertical swipe direction in Flutter

How to detect when the user swipe vertically either upward on downward?如何检测用户何时垂直向上或向下滑动?

I have been using swipedetector package, but now, it gives me exceptions like我一直在使用swipedetector包,但现在,它给了我例外

The getter 'globalPosition' was called on null.
import 'package:flutter/material.dart';

class SwipeDetectorExample extends StatefulWidget {
  final Function() onSwipeUp;
  final Function() onSwipeDown;
  final Widget child;

  SwipeDetectorExample({this.onSwipeUp, this.onSwipeDown, this.child});

  @override
  _SwipeDetectorExampleState createState() => _SwipeDetectorExampleState();
}

class _SwipeDetectorExampleState extends State<SwipeDetectorExample> {
  //Vertical drag details
  DragStartDetails startVerticalDragDetails;
  DragUpdateDetails updateVerticalDragDetails;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onVerticalDragStart: (dragDetails) {
          startVerticalDragDetails = dragDetails;
        },
        onVerticalDragUpdate: (dragDetails) {
          updateVerticalDragDetails = dragDetails;
        },
        onVerticalDragEnd: (endDetails) {
          double dx = updateVerticalDragDetails.globalPosition.dx -
              startVerticalDragDetails.globalPosition.dx;
          double dy = updateVerticalDragDetails.globalPosition.dy -
              startVerticalDragDetails.globalPosition.dy;
          double velocity = endDetails.primaryVelocity;

          //Convert values to be positive
          if (dx < 0) dx = -dx;
          if (dy < 0) dy = -dy;

          if (velocity < 0) {
            widget.onSwipeUp();
          } else {
            widget.onSwipeDown();
          }
        },
        child: widget.child);
  }
}

I ran into the same problem today, try running flutter clean , and hot restart your app.我今天遇到了同样的问题,尝试运行flutter clean ,然后热重启你的应用程序。 If this doesn't help one can always use Gesture Detector as M.Ali answered.如果这没有帮助,您可以随时使用手势检测器作为 M.Ali 的回答。 In my case a simple hot restart fixed the problem.在我的情况下,一个简单的热重启解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM