我在 Flutter 中使用 FutureBuilder 时遇到问题

时间:2021-01-06 03:04:37

标签: flutter dart flutter-futurebuilder

我在 Flutter 中使用 FutureBuilder 时遇到问题。

使用 FutureBuilder,页面会不断重建。

我省略了编写问题的详细代码。如果您想查看其他代码,请发表评论。

要阻止这种情况,我该怎么办?

Future<bool> initLikes() async {
    var list = await ApiProvider().post('/RoomSalesInfo/Select/Like', jsonEncode(
        {
          "userID" : GlobalProfile.loggedInUser.userID,
        }
    ));
      return true;
    } else {
      return false;
    }
  }

//This is the Code that I use in Widget build
FutureBuilder(
                    future: initLikes(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      //해당 부분은 data를 아직 받아 오지 못했을때 실행되는 부분을 의미한다.
                      if (snapshot.hasData == false) {
                        return SizedBox();
                      }
                      //error가 발생하게 될 경우 반환하게 되는 부분
                      // 데이터를 정상적으로 받아오게 되면 다음 부분을 실행하게 되는 것이다.
                      else {
                        return Expanded(
                          child: ListView.builder(
                              physics: ClampingScrollPhysics(),
                              shrinkWrap: true,
                              scrollDirection: Axis.vertical,
                              controller: _scrollController,
                              itemCount: GlobalProfile.listForMe.length +1,
                              itemBuilder: (BuildContext context, int index) {
                                if(index == GlobalProfile.listForMe.length){
                                  return CupertinoActivityIndicator();
                                }
                                else
                                  return  Column();
                              }


                          ),
                        );
                      }
                    })

1 个答案:

答案 0 :(得分:0)

future: initLikes(),

不要重新计算这个。新调用将覆盖旧调用。而是使用 initState() 将它计算一次到您从“future:...”引用的变量中。