Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

flutter - Error: 'await' can only be used in 'async' or 'async*' methods

I am trying to add distance from user to the Location object, but this requires using an asynchronous call that I can't figure out where and how to do exactly. From there I will sort Locations by distance from user. I tried the code below bc it's where the sorted locations would be used, but I get an error saying "await" can only be used in "async" or "async*" methods even though it is being used with an async function. How do I add distance from user to a Location object given it requires an asynchronous call?

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();
...
question from:https://stackoverflow.com/questions/65944597/error-await-can-only-be-used-in-async-or-async-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use await functions in build method because it cannot be async.To use async operations in build you must use FutureBuilder or StreamBuilder.


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...