Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment a value as the button is pressed in flutter

Tags:

flutter

dart

I am developing a calculation app where a variable is increased/decreased by a plus button and a minus button. I would like to implement a continuous increment/decrement when long-pressing (holding) the plus or minus button. How can this be done with dart/flutter?

like image 362
Anders Olsén Avatar asked Jan 25 '23 12:01

Anders Olsén


1 Answers

Just a quick sample code.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NewCode(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class NewCode extends StatefulWidget {
  @override
  _NewCodeState createState() => _NewCodeState();
}

class _NewCodeState extends State<NewCode> {
  Timer timer;
  var value = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GestureDetector(
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: Center(
                child: Text(
              'value $value',
              style: TextStyle(fontSize: 40),
            )),
          ),
          onTapDown: (TapDownDetails details) {
            print('down');
            timer = Timer.periodic(Duration(milliseconds: 500), (t) {
              setState(() {
                value++;
              });
              print('value $value');
            });
          },
          onTapUp: (TapUpDetails details) {
            print('up');
            timer.cancel();
          },
          onTapCancel: () {
            print('cancel');
            timer.cancel();
          },
        ),
      ),
    );
  }
}
like image 137
Doc Avatar answered Jan 28 '23 01:01

Doc