Home > Software design >  Async function await not awaiting
Async function await not awaiting

Time:05-26

I have an async function to upload a video using MultipartRequest. When I call my async function 'uploadVideo', by:

bool success =await uploadVideo(video,1);

The video is uploaded but it runs the next functions before finishing the upload. Why is the await is not awaiting?

static Future<bool> uploadVideo(File video, int userID) async {

var uri = Uri.parse('https://example.com/uploadFile');

Map<String, String> headers = {
  "Content-Type": "application/json",
  'Accept': 'application/json',
};

var request = http.MultipartRequest("POST", uri);

request.fields['userID'] = userID.toString();

request.headers.addAll(headers);

Uint8List data = await video.readAsBytes();
List<int> list = data.cast();

request.files.add(
await http.MultipartFile.fromBytes('File', list, filename: '.mp4'),
);

final response = await request.send();

if (response.statusCode == 200) {
  return true;
}
return false;

}

CodePudding user response:

Use await in

 request.files.add(
  await http.MultipartFile.fromBytes('File', list, filename: '.mp4'),
);

CodePudding user response:

you can write the following statement

 request.send().then((response) {
   if (response.statusCode == 200) {
       return true;
       }
    });

instead of

final response = await request.send();

if (response.statusCode == 200) {
  return true;
}
  • Related