1

我了解到将 setState(() 和 FutureBuilder 放在一起并不是一个好习惯。当我删除我的 setState(() 时,我注意到isWaiting变量不再更新到MakeCards类并保持为 True。但是当我离开时在我的 setState 中,即使它是空的setState((){ },isWaiting 也会正确更新为 False。我需要帮助理解为什么会这样,以及如何在删除我的 setState(() 时在MakeCards 中将 isWaiting更新为 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,
    );
  }
}
4

1 回答 1

0

setState您在使用时 不需要FutureBuilder.

您可以将 Future 构建器移动到小部件树的根目录(依赖于该未来数据的树的部分)

然后将通过变量传递的值替换为isWaiting快照的状态。

于 2020-10-30T19:29:05.650 回答