I have a problem about using FutureBuilder in Flutter

Issue

I have a problem about using FutureBuilder in Flutter.

With FutureBuilder, the page is continuously rebuilt.

I’ve omitted the detailed code to write the question. If you want to see additional code, please leave a comment.

To stop this, What can I do?

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();
                              }


                          ),
                        );
                      }
                    })

Solution

future: initLikes(),

Don’t recomputing this. The new invocation will overwrite the old one. Instead use an initState() to compute it just once into a variable that you reference from "future:..".

Answered By – Randal Schwartz

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *