I'm new to learning flutter and am learning about timers and progress indicators. I have made an app which has a button which on clicked shows a linear progress bar that goes from 0% to 100% in 10 seconds. The app works as expected by showing a progress bar that goes from 0% to 100% and after one more second it hides, but the value that gets incremented every second shows some odd behavior. This is the output from the console:
This is the code:
import 'dart:async';
import 'package:flutter/material.dart';
class Program4 extends StatefulWidget {
const Program4({super.key});
@override
State<Program4> createState() => _Program4State();
}
class _Program4State extends State<Program4> {
bool isProgressing = false;
double progressValue = 0.0;
Timer? progressTimer;
void progressActivity() {
setState(() {
isProgressing = true;
});
const oneSec = Duration(seconds: 1);
progressTimer = Timer.periodic(oneSec, (Timer timer) {
setState(() {
progressValue += 0.1; // Line causing the misbehavior
if (progressValue >= 1) {
progressValue = 0;
timer.cancel();
isProgressing = false;
}
});
print(progressValue);
});
}
@override
void dispose() {
progressTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Visibility(
visible: isProgressing,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Row(
children: [
const Text('0%'),
const SizedBox(width: 30),
Expanded(
child: Visibility(
child: LinearProgressIndicator(
value: progressValue,
),
),
),
const SizedBox(width: 30),
const Text('100%'),
],
),
),
),
const SizedBox(height: 50),
ElevatedButton(
onPressed: (isProgressing) ? null : progressActivity,
child: const Text('Start Progressing'),
)
],
),
);
}
}
I'm running the app on the simulator.
The parent of the center widget is Scaffold -> MaterialApp.