flutter - 是否可以在 Mobx 中拥有基于 DateTime.now 的计算属性?
问题描述
我目前正在 Dart/Flutter 中尝试这个,但我认为这个概念在其他语言中是相同的。
考虑到 'expires' 收到一个表示从现在起 2 天的日期,所以 'expired' 为 true 并且在 2 天过去后应更改为 false。
@observable
DateTime expires;
@computed
bool get expired =>
expires == null ||
expires.difference(DateTime.now()).inSeconds <= 0;
运行应用程序时,此属性不会从 true 变为 false,但在我的单元测试中,它确实如此,这就是为什么我不知道这是否可能。
单元测试供参考:
test('when expires pass its due date, it should trigger expired',
() async {
state.changeExpires(
DateTime.now().add(const Duration(seconds: 3)),
);
expect(
state.hasTokenExpired,
isFalse,
reason:
'because expires ${state.expires.toIso8601String()} should be in the interval expected to not be expired',
);
await Future.delayed(const Duration(seconds: 3));
expect(
state.hasTokenExpired,
isTrue,
reason:
'because expired ${state.expires.toIso8601String()} has not expired',
);
});
解决方案
对于 JS,有一个很好的 utils 库,它mobx-utils
具有类似的功能now()
,可以更新所有观察者、反应等。
https://github.com/mobxjs/mobx-utils/blob/master/src/now.ts
也许你可以尝试为 Dart 实现它。
推荐阅读
- javascript - ForEach - 显示来自 API 的结果
- go - 文件需要关闭吗?
- csv - Hive CSV 行分隔符配置
- python - 通过多个分隔符拆分列表
- python - 使用 pandas 聚合的自定义函数的奇怪行为
- python - Django 无法识别我的自定义用户的用户类型以进入受保护的页面视图(RelatedObjectDoesNotExist:用户没有用户类型)
- c - C:将char转换为float
- spring - 如何在 Spring 多模块项目集成测试中嵌入或模拟 kafka
- sql - 在 Netezza SQL 中创建触发器以更新另一个表
- javascript - 在旧的 IE11 中获取 base64(不使用承诺)