【发布时间】:2024-01-19 12:22:01
【问题描述】:
我正在尝试通过父类提供的回调函数(ondone)从子类传递数据(bool),该回调函数将定期调用带有布尔参数的函数。
import 'dart:async';
class Flow {
MyTimer timer;
bool done = false;
Function ondone;
Flow() {
ondone = (bool b) => done=b;
}
void addtimer(int t) {
timer = MyTimer(t, ondone);
}
}
class MyTimer {
final int time;
int remaining;
Function callback;
Timer _timer;
MyTimer(this.time, this.callback){
remaining = time;
}
void run() {
_timer = Timer.periodic(
Duration(seconds: 1),
(t) {
remaining--;
if (remaining == 0) {
_timer.cancel();
callback(true);
}
});
}
}
但我无法确定是否调用了回调,因为打印函数(在 main 中)没有打印任何包装在 if 表达式中的内容。
void main() {
var flow=Flow();
flow.addtimer(5);
flow.timer.run();
if(flow.done) print('Timer Finished..');
print('I need to run while timer is working');
}
以命令式的方式将数据从孩子传递给父母对我来说很重要(作为初学者)。
【问题讨论】:
-
您的
Timer.periodic正在运行(t) => remaining--。因此,remaining将继续变小而不会发生任何其他事情,因为您没有运行任何其他代码。 -
您从
main()拨打run()。然后整个执行此方法,包括if。因此,您正在创建一个Timer,然后立即检查if (remaining == 0),这将是false,因为您将其设置为5。 -
但是在剩余==0 之后如何从 main 运行打印功能
标签: dart timer callback message-passing