【问题标题】:Storing data in class level global variables将数据存储在类级别的全局变量中
【发布时间】: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。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的 requestUsage 是未来功能,当您在 ui 中与 FutureBuilder 一起使用它时,它永远不会刷新您每两分钟触发一次的 ui 事件。 您可以刷新您的 ui 以使用 SetState 或在您的 UI 中使用 Streams 来读取新值,而不仅仅是 FutureBuilder

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多