Flutter MaterialPageRoute WidgetBuilder runs twice

时间:2018-10-02 09:15:00

标签: dart flutter

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.

1 个答案:

答案 0 :(得分:1)

我也遇到了同样的问题。这是因为您没有向FutureBuilder添加任何条件。因此,当您使用setState()时,它将在下一次调用。

您可以使用Future函数中的标志来解决它,以便仅首次调用它。例如:

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