错误:'await'只能在'async'或'async*'方法中使用



我试图添加从用户到位置对象的距离,但这需要使用异步调用,我无法确定在哪里以及如何做。从那里我将排序位置从用户的距离。我尝试了下面的代码,它是排序位置将被使用的地方,但我得到一个错误说"等待"只能用于"async"或"异步*";方法,即使它与异步函数一起使用。我如何添加距离从用户到位置对象给定它需要异步调用?

class MapWidget extends StatefulWidget {
...
@override
_MapWidgetState createState() => _MapWidgetState();
}
class _MapWidgetState extends 
State<MapWidget> {
Future <List<Location>> sortLocations() async {
return null;//function not done
}
@override
Widget build(BuildContext context) {
final List<Location> sortedLocations = await sortLocations();
...

不能在build方法中使用await函数,因为它不能是async。要在build方法中使用异步操作,必须使用FutureBuilderStreamBuilder


Future<List<Location>> sortLocations() {
...
return <Location>[];
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Location>>(
future: sortLocations(),
builder: (context, snapshot) {
if(snapshot.hasError) {
return Center(child: Text(snapshot.error.toString()));
}
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator()));
}
return ListView(...);
},
);
}

Future<List<Location>> sortLocations() {
...
return <Location>[];
}
@override
Widget build(BuildContext context) {
return StreamBuilder<List<Location>>(
stream: sortLocations().asStream(),
builder: (context, snapshot) {
if(snapshot.hasError) {
return Center(child: Text(snapshot.error.toString()));
}
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator()));
}
return ListView(...);
},
);
}

在Flutter中有一个名为FutureBuilder的小部件,它可以帮助您在从异步函数返回数据后构建UI。你可以这样使用:

@override
Widget build(BuildContext context) {
return FutureBuilder<List<Location>>(
future: sortLocations(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Container(child: Center(child: CircularProgressIndicator()));
var sortedLocations = snapshot.data;
// Build your UI here
return ...
}
);

你不能在build方法中使用await,而是在initState中使用它

final List<Location> sortedLocations= new List();
@override
void initState(){
super.initState();
getdata();
}
getdata()async{
sortedLocations.clear();
sortedLocations = await sortLocations();
setState((){});
}

最新更新