import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _age = 1;
Timer? _timer;
bool _longPressCanceled = false;
void _increaseAge() {
setState(() {
_age++;
});
}
void _cancelIncrease() {
if (_timer != null) {
_timer!.cancel();
}
_longPressCanceled = true;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo'),
),
body: Column(
children: [
Text(_age.toString()),
GestureDetector(
child: Container(
padding: EdgeInsets.all(20),
color: Colors.lightBlue,
child: Center(child: Text('Press or long press here'))),
onTap: _increaseAge,
onLongPressEnd: (LongPressEndDetails longPressEndDetails) {
_cancelIncrease();
},
onLongPress: () {
_longPressCanceled = false;
Future.delayed(Duration(milliseconds: 300), () {
if (!_longPressCanceled) {
_timer = Timer.periodic(Duration(milliseconds: 150), (timer) {
_increaseAge();
});
}
});
},
onLongPressUp: () {
_cancelIncrease();
},
onLongPressMoveUpdate:
(LongPressMoveUpdateDetails longPressMoveUpdateDetails) {
if (longPressMoveUpdateDetails.localOffsetFromOrigin.distance >
20) {
_cancelIncrease();
}
},
)
],
),
);
}
}