在Flutter中检测垂直滑动方向

时间:2019-04-21 23:46:15

标签: dart flutter flutter-layout

如何检测用户何时垂直向上或向下滑动?

我一直在使用swipedetector软件包,但是现在,它给了我

这样的异常
The getter 'globalPosition' was called on null.

2 个答案:

答案 0 :(得分:0)

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);
  }
}

答案 1 :(得分:0)

我今天遇到了同样的问题,尝试运行flutter clean,然后热重启您的应用。 如果这样做无济于事,您可以随时使用手势检测器作为M.Ali的回答。就我而言,简单的热重启可以解决问题。