FutureBuilder,SetState:删除setState时变量未更新

时间:2020-10-30 18:16:15

标签: flutter dart setstate flutter-futurebuilder

我了解到setState(()和FutureBuilder并存不是一种好习惯。删除setState(()时,我注意到 isWaiting 变量不再更新为< em> MakeCards 类并保持True,但是当我离开setState时,即使它为空setState((){ },isisWaiting也应适当地更新为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,
    );
  }
}

1 个答案:

答案 0 :(得分:0)

使用setState时不需要FutureBuilder

您可以将Future构建器移动到小部件树的根(树的那部分取决于该future的数据)

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