使用FutureBuilder时如何仅获取一次数据? [英] How to fetch data only once when using FutureBuilder?
问题描述
我有一个获取请求,并将其作为将来传递给FutureBuilder-
I have a fetch request and I am passing it as a future to FutureBuilder -
FutureBuilder(
future: gettask(),
builder: (context, snapshot){
if(snapshot.hasData){
// Stopwatch stopwatchbefore = new Stopwatch()..start();
// print('futurebuilder executed in ${stopwatchbefore.elapsed}');
return SingleChildScrollView(child: listViewWidget(snapshot.data));
}else{
return Center(child: CircularProgressIndicator());
}
},
)
然而,方法gettask()似乎在重复获取事件.我尝试使用 https://pub.dev/packages/memoize 和
The method gettask() however, seems to be fetching events repeatedly. I tried to use https://pub.dev/packages/memoize and https://api.flutter.dev/flutter/package-async_async/AsyncMemoizer-class.html but i think they are deprecated since it says that AsyncMemoizer is undefined (no import option available).
我也尝试过 https://github.com/flutter/flutter /issues/11426#issuecomment-414047398 但我想探索类似于备忘录的选项.
I have also tried https://github.com/flutter/flutter/issues/11426#issuecomment-414047398 But i wanted to explore an option similar to memoizer.
有什么方法可以只获取一次数据(类似于备忘录)?
are there any alternatives to fetching data only once (something similar to memoizer)?
推荐答案
使用StatefulWidget
,然后在State
内创建一个Future
变量(如_getTaskAsync
).
Use StatefulWidget
, then create an Future
variable (like _getTaskAsync
) inside State
.
将gettask()
分配给initState
中的该将来变量.
Assign gettask()
to that future variable in initState
.
然后使用该变量作为FutureBuilder
的参数(例如future: _getTaskAsync
)
Then use that variable as argument to FutureBuilder
(like future: _getTaskAsync
)
代码:
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Future _getTaskAsync;
...
@override
void initState() {
_getTaskAsync = gettask();
super.initState();
}
...
FutureBuilder(
future: _getTaskAsync,
builder: (context, snapshot) {
if (snapshot.hasData) {
//Stopwatch stopwatchbefore = new Stopwatch()..start();
//print('futurebuilder executed in ${stopwatchbefore.elapsed}');
return SingleChildScrollView(child: listViewWidget(snapshot.data));
} else {
return Center(child: CircularProgressIndicator());
}
},
);
请参阅文档
这篇关于使用FutureBuilder时如何仅获取一次数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!