Q: Flutter update progressbar from nested class I want to update the value of the progress bar from nested class.
I passed the callback to foo function expecting it would update my progress bar with setState() each iteration of counter.
Problem: progress bar gets updated only after foo function fully finished. I guess the problem is somewhere in the event loop...
Main screen:
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _progressBarVal = 0;
  final Counter _counter = Counter();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          TextButton(
            onPressed: () {
              _counter.foo((val) {
                setState(() {
                  _progressBarVal = val;
                });
              });
            },
            child: const Text('Press me'),
          ),
          LinearProgressIndicator(
            value: _progressBarVal,
          ),
        ],
      ),
    );
  }
}

Counter class:
class Counter {
  void foo(Function(double val) barCallback) {
    for (int i = 0; i <= 10; ++i) {
      barCallback(i / 10);
      debugPrint('Val is ${i / 10}');
      sleep(const Duration(seconds: 1));
    }
  }
}


A: Use  Future.delayed instead of sleep
class Counter {
  void foo(Function(double val) barCallback) async {
    for (int i = 0; i <= 10; ++i) {
      barCallback(i / 10);
      debugPrint('Val is ${i / 10}');
      await Future.delayed(const Duration(seconds: 1));
    }
  }
}


