0

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:

enter image description here

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.

  • I don't know if this will fix it, but why not use int instead of double? Then you can count from 0 to 10 instead of 0.0 to 1.0. – SilkeNL Jun 05 '23 at 14:13
  • int works. But I wanted to know why I cannot achieve the same behavior with double. Why does double misbehave like that? – Twisha Solgama Jun 06 '23 at 06:57

0 Answers0