Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

api - Flutter FutureBuilder gets constantly called

I'm experiencing interesting behavior. I have a FutureBuilder in Stateful widget. If I return FutureBuilder alone, everything is ok. My API gets called only once. However, if I put extra logic, and make a choice between two widgets - I can see in chrome my API gets called tens of times. I know that build method executes at any time, but how does that extra logic completely breaks Future's behavior?

Here is example of api calling once.

@override
  Widget build(BuildContext context) {
    return FutureBuilder(..);
}

Here is example of api being called multiple times if someBooleanFlag is false.

@override
  Widget build(BuildContext context) {
    if(someBooleanFlag){
      return Text('Hello World');
    }
    else{
    return FutureBuilder(..);
}

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even if your code is working in first place, you are still not using it properly. As stated in the official documentation of Future Builder,

The future must be obtained earlier, because if the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

The correct way to do this is:

// Create an instance variable.
Future myFuture;

@override
void initState() {
  super.initState();
  
  // Assign that variable your Future.
  myFuture = getFuture();
}

@override
Widget build(BuildContext context) {
  return FutureBuilder(
      builder: myFuture, // Use that variable here.
      ...
  );
}  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...