我了解到,将setState(() )和FutureBuilder放在一起并不是很好的实践。当我删除我的setState(() )时,我注意到isWaiting变量不再更新到MakeCards类中,而是停留在True。但是,当我离开我的setState时,即使它是空的setState((){ },isWaiting也会正确地更新为False。我需要帮助理解为什么是这样,以及如何在删除isWaiting (())的同时将MakeCards中的setState更新为False。
bool isWaiting = true; <------------------------------------------
Future<Map> getData() async {
try {
List<String> coinData = await CoinData();
Map<String, List<String>> graphData = await GraphData()
setState(() { <------------------------------------
coinValues = coinData;
graphValues = graphData;
});
isWaiting = false; <----------------------------------
.
. (some code)
.
return allDataValues;
}构建方法
MakeCards(
isWaiting: isWaiting, <-----------------------------
selectedCurrency: selectedCurrency,
coinData: allDataValues['lastCoinPrices'])
.makeCards(),
FutureBuilder<Map>(
future: futureData,
builder: (context, snapshot) {
print("FutureBuilder started");
if (!snapshot.hasData)
return CircularProgressIndicator();
else if (snapshot.data.isEmpty)
return Container();
else {
print("FutureBuilder completed");
return Graph(snapshot.data);
}
})MakeCards (独立文件)
class MakeCards {
MakeCards({this.isWaiting, this.selectedCurrency, this.coinData});
bool isWaiting;
String selectedCurrency;
List<String> coinData = [];
Row makeCards() {
List<CryptoCard> cryptoCards = [];
for (int i = 0; i < cryptoAbbreviation.length; i++) {
cryptoCards.add(
CryptoCard(
cryptoCurrency: cryptoAbbreviation[i],
selectedCurrency: selectedCurrency,
value: isWaiting ? '---' : coinData[i], <-------------------------
name: cryptoName[i],
// iconContent: iconContent,
),
);
}
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: cryptoCards,
);
}
}发布于 2020-10-30 19:29:05
您在使用setState时不需要FutureBuilder。
您可以将未来构建器移动到小部件树的根(取决于来自该未来的数据的树的部分)。
然后将通过变量isWaiting传递的值替换为快照的状态。
https://stackoverflow.com/questions/64613770
复制相似问题