Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increase number Periodically in Flutter

I am two Lists, List numList and List timeList. Every time I click a button firstly I add 1 to numList and DateTime.now() to timeList.

When I longPress this button, I want a variable on screen to add each value from numList and inBetween wait eah Duration from timeList.

I cant figure out what function should I write, I will attach my code below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 import 'package:flutter/material.dart';

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

class TapCounterApp extends StatelessWidget {
  const TapCounterApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Tap Counter',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _counter = 0;
  List<int> _numberList = [];
  List<DateTime> _durationList = [];

  void _onTap() {
    setState(() {
      _counter++;
      _numberList.add(1);
      _durationList.add(DateTime.now());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text('Your Tap Simulation - 0'),
            Text('TapCounter - $_counter'),
          ],
        ),
      ),
      //------------------------------------------------------------------------
      floatingActionButton: InkWell(
        onTap: _onTap,
        onLongPress: () {},
        child: const CircleAvatar(
          radius: 30,
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

>Solution :

You can try using this method:

  int _tapCount = 0;

  void _simulateTaps() async {
    for (int i = 0; i < _numberList.length; i++) {
      _tapCount += _numberList[i];
      setState(() {
        _tapCount = _tapCount;
      });

      Duration delay = (i < _durationList.length - 1)
          ? _durationList[i + 1].difference(_durationList[i])
          : Duration.zero;

      await Future.delayed(delay);
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading