Flutter-如何不一遍又一遍地调用同一个服务?

Flutter- How NOT to call the same Service over and over?

假设我的目标是向用户显示“无穷无尽”的推荐项目列表。

为此,我实现了一些非常昂贵的异步方法 getItemsFromServer(...)(在服务器使用、时间、电池等方面)并从服务器,并通过添加从服务器获取的项目来更新推荐项目屏幕的状态。

我的目标是仅当用户有少于 20 个他尚未查看的项目时才调用此函数。 问题是如果我天真地编程,例如

if(itemsNotViewed<20){
getItemsFromServer(...)
}

在用户点击或查看某个新项目后,此异步方法将被调用大约 20 次... 什么是最有原则的方法只调用一次并等待它完成,同时又不干扰用户的体验?

未来对象本身对于记住是否正在发生某事非常有用。这样的事情应该有效。理想情况下,您可以将其放入从多个位置调用的函数中。

class MyState ... {

  Future itemsBeingGotten;


  build() {
    ...
      onPress: () async {
        if (itemsBeingGotten == null && itemsNotViewed < 20) {
          try {
            itemsBeingGotten = getItemsFromServer()
            await itemsBeingGotten; 
          } finally {
            itemsBeingGotten = null;
          }
        }
      }
  }