本文介绍了Flutter FutureBuilder 不断被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我遇到了有趣的行为.我在有状态小部件中有一个 FutureBuilder.如果我单独返回 FutureBuilder,则一切正常.我的 API 只被调用一次.但是,如果我添加额外的逻辑,并在两个小部件之间做出选择 - 我可以在 chrome 中看到我的 API 被调用了数十次.我知道 build 方法会随时执行,但是这个额外的逻辑如何完全破坏 Future 的行为?

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?

这里是api调用一次的例子.

Here is example of api calling once.

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

如果 someBooleanFlagfalse,这里是 api 被多次调用的例子.

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

谢谢

推荐答案

即使您的代码在第一时间工作,您仍然没有正确使用它.如Future Builder的官方文档所述,

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,

future 必须提前获取,因为如果 future 和 FutureBuilder 是同时创建的,那么每次 FutureBuilder的父级重建,异步任务将重新启动.

正确的做法是:

// 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.
      ...
  );
}

这篇关于Flutter FutureBuilder 不断被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:25