我想从嵌套类更新进度条的值。
我将回调传递给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));
}
}
}
1条答案
按热度按时间mw3dktmi1#
使用
Future.delayed
代替sleep