首页 > 解决方案 > 即使在本地数据中,Flutter future builder 也会触发

问题描述

我从我的 API 中获取数据,然后将这些数据(标签 = id + 名称)保存在一个单例中。我的单例是空的,我调用 API,否则,我调用我的“会话”数据。

但是每次单击我的标签之一时,我的 FutureBuilder 总是重新加载

所以这是我的建造者

child: FutureBuilder(
          future: PopularTags.getPopularTags(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              List<Tag> popularTags = snapshot.data;
              return _generateTags(popularTags);
            } else {
              return Center(
                child: SizedBox(
                  height: 25,
                  width: 25,
                  child: CircularProgressIndicator(),
                ),
              );
            }
          },
        ),

这就是它完成的原因。由于我添加了 setState(),所以我得到了这个结果

Wrap _generateTags(List popularTags) { List tagsWidget = [];

for (int i = 0; i < popularTags.length; i++) {
  Color selectedState = AppColors.TagNotSelectBackground;
  Tag currentTag = popularTags[i];
  Container tmp = Container(
    child: Padding(
      padding: const EdgeInsets.only(
        left: 0,
        right: 2,
        bottom: 2,
      ),
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (widget.selectedTags.contains(currentTag)) {
              print("tag remove : " + currentTag.tag);
              widget.selectedTags.remove(currentTag);
              selectedState = AppColors.TagNotSelectBackground;
            } else {
              print("tag add : " + currentTag.tag);
              selectedState = AppColors.TagSelectBackground;
              widget.selectedTags.add(currentTag);
            }
            print(selectedState);
          });
        },
        child: Container(
          decoration: BoxDecoration(
            color: widget.selectedTags.contains(currentTag)
                ? AppColors.TagSelectBackground
                : selectedState = AppColors.TagNotSelectBackground,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(currentTag.tag),
          ),
        ),
      ),
    ),
  );
  tagsWidget.add(tmp);
}

Wrap wrap = Wrap(
  children: tagsWidget,
);

return wrap;

}

这两行代码都放在一个单独的有状态小部件中

这就是我如何称呼标签:

  static Future<List<Tag>> getPopularTags() async {
    print('--load tags---');
    Singleton singleton = Singleton();
    if (singleton.popularTags.length > 0) {
      return singleton.popularTags;
    }
    else return apiData(); }

那么如何防止我的 getPopularTags() 在我每次点击标签时加载?

编辑:稍后,应用程序应该能够在 3 分钟后自动重新加载标签,也许 AsyncMemoizer 应该或不应该做这项工作?

标签: fluttersetstate

解决方案


推荐阅读