NCSantos
NCSantos

Reputation: 31

Flutter MaterialPageRoute WidgetBuilder runs twice

I'm creating a page that has a TextField, when user enters 3+ char in it I fetch rows, from a database, that contain the inserted text. In the example I provide I simulate this by getting a List. After this a list is presented to the user, the user can tap one of the rows to go to another page.

gist example

My problem is that when I tap a row MaterialPageRoute WidgetBuilder runs twice, this is the log:

---------- onTap ----------
---------- MaterialPageRoute ----------
---------- SecondPage build ----------
---------- MaterialPageRoute ----------
---------- SecondPage build ----------

Can someone explain this behavior and also how to fix it?

Thanks.

Upvotes: 1

Views: 2471

Answers (1)

A_Rush
A_Rush

Reputation: 378

I have faced the same problem. This is because you didn't add any condition to FutureBuilder. So when you are using setState() it gets called for the next time.

You can solve it using a flag in Future function so that it is invoked for the first time only. Eg:

bool flag = true;
flag?FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snap){
  if(snap.connectionState != ConnectionState.done){
     return Center(child: CircularProgressIndicator(),);
  }else{
     return populate();
  }
},
):Container();
 Future getData()async{
    flag = false;
    return await fetchFromDatabase();
 }

Upvotes: 1

Related Questions