【发布时间】:2022-11-28 16:40:13
【问题描述】:
我想从嵌套类更新进度条的值。
我将回调传递给 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));
}
}
}
【问题讨论】: