嵌套类中的Flutter更新进度条

ni65a41a  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(144)

我想从嵌套类更新进度条的值。
我将回调传递给foo函数,期望它在每次计数器迭代时使用setState()更新我的进度条。
问题:只有在foo函数完全完成后,进度条才会更新。我猜问题出在事件循环的某个地方...
主画面:

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,
          ),
        ],
      ),
    );
  }
}

计数器类别:

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));
    }
  }
}
mw3dktmi

mw3dktmi1#

使用Future.delayed代替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));
    }
  }
}

相关问题