Stuck Loader in FutureBuilder



我是Flutter和Dart的新手,我试图在加载页面的过程中进行扩展计算,但当我尝试这样做时,加载程序被卡住了:

body: Center(
child:FutureBuilder(
future:   _lorem()
builder:  (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done){
print("loader");
return Center(
child: CircularProgressIndicator(
backgroundColor:  Theme.of(context).primaryColor)
);
} 

[…]

Future<void> _lorem() async {
//there is not a request to service, there is a more than one filter on map and some lists. I set the for loop for example of a local computation
return Future(() {
for (int i = 0; i < 50000; i++){
print(i);
}
}
);
}

我认为实现这一点的更简单方法是在小部件中使用类型为Completer的字段,例如Completer calc。您可以在小部件初始化中开始昂贵的计算(从不在构建函数中(,当计算完成时,您可以通过调用calc.complete()completeCompleter

在小部件的FutureBuilder中,您应该通过包含future: calc.future而不是future: _lorem()来监听calc的未来。

请参阅FutureBuilder以获取此UI范例的示例。

用Future和计算求解。

详细信息:

Future<List<CustomObject>> _retrieveCustomObjects() async {
SourceData data = SourceData(CustomSourceData());
return compute(getFilteredClients, data);
}
List<CustomObject> computeCustomObject(SourceData data) {
List<CustomObject> list = [];
// expensive logic on data, not only network call
return list;
}
class LoremIpsumClass { 
// use where you need `List<CustomObject> value = await _retrieveFilteredClient();`
}

相关内容

  • 没有找到相关文章