how to show 'for' loop progress Indicator in flutter

Issue

I have a loop that prints "hello world" 100 times. so what i want is to show progress Indicator which shows the loop progress..
for example: if the loop printed 50 time from total 100 time the progress Indicator should be at 50 percent..

Solution

Like @pskink mentioned in the comments, a LinearProgressIndicator or CircularProgressIndicator should do the trick. Do go into a bit more detail, you can store the progress after each iteration (or every so many iterations depending on your needs), and if you use your widget’s state for it, a rebuild should automatically trigger and rebuild the progress indicator with the new value each time. That could look a bit like:

// inside the State
double progress = 0.0;

doTheLoop() {
  for (int i = 0; i < 100; i++) {
    print('Hello world');
    setState(() => progress = i/100);
  }
}

build(BuildContext context) {
  return Column(children: [
    Container(
      // the progress indicator updates when the progress variable in the state updates, since a rebuild is triggered
      child: LinearProgressIndicator(
        progress: progress,
      );
    ),
    
    // press the button to start the loop
    ElevatedButton(
      child: Text('Start loop'),
      onPressed: doTheLoop,
    ),
  ],),
}

Answered By – fravolt

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *