'Await doesn't wait in Flutter with external API (code attached)

I have a function that loops through a list of images and gets a response from an external API, however, no matter what I try, the function never waits for the detectImage to actually have a response. Please find below my code currently! Any help is much appreciated! The function below:

await Future.delayed(Duration(seconds: 5), () async {
      final routeArgs =
          ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
      model = routeArgs["product"];
      DecectService instance = DecectService();
      await instance.detectImage(model);
      print("instance");
      print(instance.category);
      if (instance.category == null) {
        await _showMyDialog();
      } else {
        Navigator.pushReplacementNamed(context, 'add_categories', arguments: {
          "product": this.model,
          'response': instance.category,
        });
        String category = routeArgs["response"];
        print(category);
      }
    });

Calls a function in this class:

class DecectService {
  String category;
  List images = [];
  DecectService({this.images});

  Future<String> detectImage(Product model) async {
    print("Here");
    List detections = [];
    var map = Map();
    //List detections = await detectionsfun(model);
    for (var img in model.images) {
      final url = "SomeIPAdress";
      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.files.add(http.MultipartFile('images',
          File(img.src).readAsBytes().asStream(), File(img.src).lengthSync(),
          filename: img.src.split("/").last));
      var res = await request.send();
      var response = await res.stream.bytesToString();
      var categoryResponse = await jsonDecode(response);
      final d = Detector.fromJson(categoryResponse);
      category = d.response.first.detections.first.detectionClass;
      print(category);
      detections.add(category);
    }
    // var map = await detectionsfun(model);
    for (var element in detections) {
      if (element != null) {
        if (!map.containsKey(element)) {
          map[element] = 1;
        } else {
          map[element] += 1;
        }
      }
    }
    var sortByValue = new SplayTreeMap<String, int>.from(
        map, (key1, key2) => map[key1].compareTo(map[key2]));
    List categories = sortByValue.keys.toList();
    if (categories.isNotEmpty) {
      String answer = categories.last;
      category = answer;
    }
    return category;
  }
}


Solution 1:[1]

Try calling your operations after the delay, not as its callback:

void someFunction() async{

 await Future.delayed(Duration(seconds: 5);
 final routeArgs =
          ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
      model = routeArgs["product"];
      DecectService instance = DecectService();
      await instance.detectImage(model);
      print("instance");
      print(instance.category);
      if (instance.category == null) {
        await _showMyDialog();
      } else {
        Navigator.pushReplacementNamed(context, 'add_categories', arguments: {
          "product": this.model,
          'response': instance.category,
        });
        String category = routeArgs["response"];
        print(category);
      }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kerim