Flutterラボの
プレミアム会員になる
【Flutter】ダブルタップを検知する(GestureDetector)

#プログラミング#アプリ開発#Flutter#dart
onTapやonPressedでシングルタップを検知することはよくありますが、ダブルタップも簡単に検知できるのでその方法を紹介します。
GestureDetectorウィジェトのonDoubleTapプロパティで検知できます。
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
String _text = '';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
width: double.infinity,
height: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(_text, style: const TextStyle(fontSize: 30),),
GestureDetector(
child: Container(
width: 200,
height: 200,
color: Colors.red,
),
onTap: () {
setState(() {
_text = 'シングルタップ';
});
},
onDoubleTap: () {
setState(() {
_text = 'ダブルタップ';
});
},
),
],
),
),
);
}
}
GestureDetectorでダブルタップ以外にも、ロングタップやドラッグなどいろいろな動作が取得できるのでぜひ使ってみてください。
ちなみに、シングルタップだけしかないときよりも、ダブルタップがあるときのほうがシングルタップの検知が遅くなるのでご注意ください。