Flutter FutureBuilder不断被称为 [英] Flutter FutureBuilder gets constantly called
问题描述
我正在经历有趣的行为.我在有状态的小部件中有一个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(..);
}
以下是如果someBooleanFlag
为false
的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(..);
}
谢谢
推荐答案
即使您的代码排在第一位,您仍然无法正确执行操作,正确的方法是:
Even if your code is working in first place, you are still not doing it properly, the correct way to do is:
// Create instance variable
Future myFuture;
@override
void initState() {
super.initState();
// assign this variable your Future
myFuture = getFuture();
}
@override
Widget build(BuildContext context) {
if (someBooleanFlag) {
return Text('Hello World');
} else {
return FutureBuilder(
future: myFuture, // use it like this
...
);
}
}
这篇关于Flutter FutureBuilder不断被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!