flutter - 使用 Flutter DateTime 和 Timer 时遇到不一致的行为
问题描述
在使用 Flutter 的 DateTime 类时,我注意到一些不一致的地方。Timer 和 DateTime 似乎不一致。当我打印当前秒数时,我看到输出不是我期望看到的。我需要这方面的帮助。这是我的代码:
DateTime now = new DateTime.now();
print(now.second.toString());
print('SENDING POS');
Timer(Duration(seconds: 3), () {
// 3s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
print('POS DONE');
print('SENDING REFL');
});
Timer(Duration(seconds: 3), () {
// 3s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
// 5s over, send the other message
print('REFL DONE');
print('SENDING PROJ LINES');
});
Timer(Duration(seconds: 15), () {
// 15s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
print('PRJL DONE');
print('SENDING HEIG');
});
Timer(Duration(seconds: 15), () {
// 15s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
pdps.dismissDataBundleDialog(pdps.context);
print('HEIG DONE');
});
我的预期输出应该是:
2
SENDING POS
5
POS DONE
SENDING REFL
8
REFL DONE
SENDING PROJ LINES
23
PRJL DONE
SENDING HEIG
38
DISMISS
HEIG DONE
但我看到的是:
2
SENDING POS
5
POS DONE
SENDING REFL
5
REFL DONE
SENDING PROJ LINES
17
PRJL DONE
SENDING HEIG
17
DISMISS
HEIG DONE
我该如何解决这种行为?
提前致谢
解决方案
使用 then() 链解决它:
DateTime now = new DateTime.now();
print(now.second.toString());
print('SENDING POS');
Future.delayed(Duration(seconds: 3), () {
// 3s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
print('POS DONE');
print('SENDING REFL');
}).then((value) => {
Future.delayed(Duration(seconds: 3), () {
// 3s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
// 5s over, send the other message
print('REFL DONE');
print('SENDING PROJ LINES');
}).then((value) => {
Future.delayed(Duration(seconds: 15), () {
// 15s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
print('PRJL DONE');
print('SENDING HEIG');
}).then((value) => {
Future.delayed(Duration(seconds: 15), () {
// 15s over, send the other message
DateTime now = new DateTime.now();
print(now.second.toString());
pdps.dismissDataBundleDialog(
pdps.context);
print('HEIG DONE');
})
})
})
});
推荐阅读
- javascript - “web-request”包的依赖问题。无法解析 'stream'、'tls'、'zlib'、'path'、'net'、'https'、'http'、'fs'、'crypto'
- gitpython - 使用 GitPython 查找 repo 的第一个提交(时间戳详细信息)
- java - 需要帮助在 Graphics2D 中调整缩放系统 - Java
- jquery - 如何在 Vue 组件中导入或包含 jquery 及其插件?
- ruby-on-rails - 格式化黎曼电子邮件
- reactjs - 反应 TextField 材质 UI 值
- python - 大数据框中的聚类:使用 .loc[row_indexer,col_indexer] 代替 np.select
- python - 将 python vcr 与 Google Video Intelligence 一起使用 - 请求出错
- javascript - 如何让我的数据出现在嵌套对象上?
- python - VSCode Intellisense 显示错误的自动完成模块