forked from picnic-app-cool/picnic-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswipe_detector.dart
76 lines (67 loc) · 2.07 KB
/
swipe_detector.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import 'package:flutter/material.dart';
/// GestureDetector specialized in detecting swipes in various directions
class SwipeDetector extends StatefulWidget {
const SwipeDetector({
super.key,
this.onSwipeLeft,
this.onSwipeRight,
this.onSwipeDown,
this.onSwipeUp,
this.swipeThreshold = defaultSwipeThreshold,
required this.child,
}) : assert(
onSwipeLeft != null || onSwipeRight != null,
'you have to provide at least one listening callback, f.e: onSwipeLeft',
);
static const defaultSwipeThreshold = 20.0;
final VoidCallback? onSwipeLeft;
final VoidCallback? onSwipeRight;
final VoidCallback? onSwipeDown;
final VoidCallback? onSwipeUp;
// what distance needs to be dragged in single update to detect it as swipe.
final double swipeThreshold;
final Widget child;
@override
State<SwipeDetector> createState() => _SwipeDetectorState();
}
class _SwipeDetectorState extends State<SwipeDetector> {
bool _notified = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onHorizontalDragCancel: () => _notified = false,
onHorizontalDragEnd: (end) => _notified = false,
onHorizontalDragUpdate: _horizontalDragUpdate,
onVerticalDragCancel: () => _notified = false,
onVerticalDragEnd: (end) => _notified = false,
onVerticalDragUpdate: _verticalDragUpdate,
child: widget.child,
);
}
void _verticalDragUpdate(DragUpdateDetails update) {
final dy = update.delta.dy;
if (_notified) {
return;
}
if (dy > widget.swipeThreshold) {
_notified = true;
widget.onSwipeDown?.call();
} else if (dy < -widget.swipeThreshold) {
_notified = true;
widget.onSwipeUp?.call();
}
}
void _horizontalDragUpdate(DragUpdateDetails update) {
final dx = update.delta.dx;
if (_notified) {
return;
}
if (dx > widget.swipeThreshold) {
_notified = true;
widget.onSwipeRight?.call();
} else if (dx < -widget.swipeThreshold) {
_notified = true;
widget.onSwipeLeft?.call();
}
}
}