我正在使用FutureBuilder
从数据库调用中构建一个来自未来的项目列表。由于某些原因,当我调用setState()
时,FutureBuilder
会运行两次,这是有问题的。我已经制作了一个简化版本的代码来说明这个问题:
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仍然是输出),然后立即再次调用,它被删除了。
这里发生什么事情?
发布于 2020-09-11 03:59:14
我仍然不能百分之百确定为什么它会运行两次,但是第一次“不正确”的运行,connectionstate正在等待,第二次“正确”的运行“完成”了。所以我用一个简单的if语句解决了这个问题。
https://stackoverflow.com/questions/63828512
复制相似问题