How to set counter to working onLongPress and onTap same time?

736 Views Asked by At

I just started to Flutter. And as you know, Flutter have a demo project in the start. Each time I click, the number increases. But i want to when I hold it down the screen, the numbers to increase at a certain speed. But at the same time, the one-click command should remain. I hope i could tell the thing. I putted the GestureDetector and something to customize the code, as you see. So how can do this by adding what ? Please show me by this code, i really appreciate it. Thanks in advance!




import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Ana Sayfa'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _counter++;
        });
      },
      child: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Click Anywhere',
              ),
              Text(
                '$_counter',
              ),
            ],
          ),
        ),
      ),
    );
  }
}
1

There are 1 best solutions below

2
On BEST ANSWER

This can be archived by using a Timer that will be activated when someone long presses the button or something and will be deactivated once the button is released. To do that:

Import dart async:

import 'dart:async';

Define an empty timer:

Timer? timer;

use onLongPress property of GestureDetector to start the timer that will periodically increase the counter:

onLongPress: (){
 timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
  setState(() {
    _counter++;
   });
 });
},

and use onLongPressEnd to stop the timer when the long press is released:

onLongPressEnd: (details){
  timer?.cancel();
},

PS: Lower the milliseconds to speed up the counter speed.