Detect vertical swipe direction in Flutter

后端 未结 2 1621
南笙
南笙 2020-12-21 13:13

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



        
2条回答
  •  借酒劲吻你
    2020-12-21 13:47

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

提交回复
热议问题