How to get details on onDoubleTap in Flutter
Hello!
Recently, I wrote an article about how to create a “like” animation similar to Instagram’s. The idea is that when you double-tap anywhere on a photo, a heart appears under your finger and then flies off the screen. It looks great, but I encountered a problem: GestureDetector
I was using to detect gestures doesn't have details
for the onDoubleTap
event and lacks an onDoubleTapUp
event that could have this data.
So, I had to create my own implementation of the onDoubleTap
detector.
Here’s the code:
class DoubleTapDetector extends StatefulWidget {
const DoubleTapDetector({
super.key,
required Widget child,
required GestureTapDownCallback onDoubleTap,
}) : _child = child,
_onDoubleTap = onDoubleTap;
final Widget _child;
final GestureTapDownCallback _onDoubleTap;
@override
State<DoubleTapDetector> createState() => _DoubleTapDetectorState();
}
class _DoubleTapDetectorState extends State<DoubleTapDetector> {
TapDownDetails? _tapDownDetails;
@override
Widget build(BuildContext context) {
return GestureDetector(
onDoubleTapCancel: () => _tapDownDetails = null,
onDoubleTapDown: (details) => _tapDownDetails = details,
onDoubleTap: () {
if (_tapDownDetails == null) return;
widget._onDoubleTap(_tapDownDetails!);
},
child: widget._child,
);
}
}
Let’s break down the implementation.
As you can see, there is onDoubleTapDown
method that contains the necessary details. The widget stores this data in the state, and then onDoubleTap
can provide this data. Also we clean this data on onDoubleTapCancel
.
To use this widget, wrap any widget like this:
DoubleTapDetector(
child: const SizedBox.square(
dimension: 100,
),
onDoubleTap: (details) => print('Double details: $details'),
);
And that’s it! A simple solution that works.
If this article is useful for you, don’t hold back — give it a clap! 😊
Bye!