【发布时间】:2021-07-25 05:24:17
【问题描述】:
我有 home.dart 类,它在构建时获取 api 结果并分配响应以及获取的时间 (DateTime.now())。
这里是 StatefulWidget Home 类
class HomeView extends StatefulWidget {
int maxCacheDurationInMinutes = 2;
DateTime _lastUpdatedTime;
Usage previousFetchedUsage;
@override
_HomeView createState() => _HomeView();
}
在状态上,我像这样使用widget._lastUpdatedTime 访问元素。
这是状态类和请求函数
class _HomeView extends State<HomeView> {
bool get isValidCache =>
widget._lastUpdatedTime != null &&
DateTime.now().difference(widget._lastUpdatedTime).inMinutes <
widget.maxCacheDurationInMinutes;
int get minsSinceLastCached => widget._lastUpdatedTime != null
? DateTime.now().difference(widget._lastUpdatedTime).inMinutes
: 0;
Future<Usage> requestUsage(BuildContext context) async {
if (isValidCache) {
// is valid cache
if (widget.previousFetchedUsage != null) {
// return cached if it isn't null
return widget.previousFetchedUsage;
}
}
// if cache is invalid or cache is null
// fetch the latest data and assign to cache variable
widget._lastUpdatedTime = DateTime.now();
return widget.previousFetchedUsage = await ClientHandler.of(context).client.fetchUsage();
}
}
// some code is omitted to keep it brief
这里的问题是,在每次 UI 重建时(在热重载期间),都会发送请求。从技术上讲,它应该在 2 分钟内只发送一次。
我还尝试使用 make previousFetchedUsage 作为静态变量。仍然没有任何变化。
在 dart 中有什么我应该注意的概念吗?我来自 C# 背景,最近开始使用 Flutter。
【问题讨论】: