首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么setState会触发2次FutureBuilder运行?

为什么setState会触发2次FutureBuilder运行?
EN

Stack Overflow用户
提问于 2020-09-10 19:14:37
回答 2查看 95关注 0票数 0

我正在使用FutureBuilder从数据库调用中构建一个来自未来的项目列表。由于某些原因,当我调用setState()时,FutureBuilder会运行两次,这是有问题的。我已经制作了一个简化版本的代码来说明这个问题:

代码语言:javascript
运行
复制
void initState() {
  super.initState();
  futureIng = db.getIngredients();
}

Widget build(BuildContext context) {
  return Column(
    children: [
      getButton(),
      getDeleteButton(),
      FutureBuilder<List<IngredientSql>>(
        future: futureIng,
        builder: (BuildContext context, AsyncSnapshot<List<IngredientSql>> snapshot) {
          if (snapshot.hasData && snapshot.data != null) {
            if (snapshot.data.isEmpty) {
              return Text("Nothing yet", style: TextStyle(color: Colors.white));
            }
            return Text(getList(snapshot.data));
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
    ],
  );
}
}

void insertIngredient() {
Future<bool> success = db.insertIngredient("banana2"));
success.then((success) {
  if (success) {
    setState(() {
      futureIng = db.getIngredients();
    });
});


}

void deleteIngredient() {
var future = db.deleteIngredient("banana2");
future.then((value) {
  futureIng = db.getIngredients();
  futureIng.then((value) {
    setState(() {
      print("asd");
    });
  });
});


}

getButton()调用insertIngredient(),按getDeleteButton()调用deleteIngredient()

因此,我首先插入"banana2“成分,然后按delete键删除它。正如您在deleteIngredient()函数中看到的,该项被删除,然后我更新未来并调用setState()重新构建输出文本。然而,FutureBuilder现在被调用了2次,一次没有发生任何事情(banana2仍然是输出),然后立即再次调用,它被删除了。

这里发生什么事情?

EN

Stack Overflow用户

发布于 2020-09-11 03:59:14

我仍然不能百分之百确定为什么它会运行两次,但是第一次“不正确”的运行,connectionstate正在等待,第二次“正确”的运行“完成”了。所以我用一个简单的if语句解决了这个问题。

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63828512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档