3

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

The getter 'globalPosition' was called on null.
M.Ali
  • 8,815
  • 5
  • 24
  • 42
  • You're probably looking for [`GestureDetector`](https://docs.flutter.io/flutter/widgets/GestureDetector-class.html). I'm not sure why that swipedetector package exists because I could have sworn GestureDetector has been around for a long time, but in any case it seems that the repository no longer exists. – Herohtar Apr 22 '19 at 21:40
  • GestureDetector is the core widget. You can use SwipeDetector to do different things for every swipe direction. Of course you can make your own widget but of course it's easier if there is a widget ready to use. Though it lacks null safety and while I tried to make it null safe, it crashes sometimes because direction is not set. – Plato Nov 02 '22 at 11:35

2 Answers2

8
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);
  }
}
M.Ali
  • 8,815
  • 5
  • 24
  • 42
0

I ran into the same problem today, try running flutter clean, and hot restart your app. If this doesn't help one can always use Gesture Detector as M.Ali answered. In my case a simple hot restart fixed the problem.

Yash Sharma
  • 169
  • 13