Advertisements
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.
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);
}
}