Home > database >  Flutter await does not await until return of function
Flutter await does not await until return of function

Time:06-30

I tried to find an answer but my problem is still there.

In my asynchronous upload function I return at the and the generated name of the image, which I want to use to make my database request.

This is my upload function:

Future<String> upload(File imageFile) async {
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    // get file length
    var length = await imageFile.length();

    var uri = Uri.parse("http://localhost:8080/upload");

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

    var multipartFile = new http.MultipartFile('file', stream, length,
        filename: basename(imageFile.path));

    request.files.add(multipartFile);

    var response = await request.send();
    print(response.statusCode);

    var createdFileName = "";
    response.stream.transform(utf8.decoder).listen((value) {
      createdFileName = value;
      print(createdFileName);
    });
    return createdFileName;
  }

I call it like this:

 List createdFileNames = [];
      for (var e in imagefiles) {
          createdFileNames.add(await upload(File(e)));
      }

I don't know why, but the createdFileNames are ["",""], but the upload gives as result the right name. In debug mode I can see, that the loop does not wait until the upload has finished.

Do you have any suggestions?

Thank you very much!

CodePudding user response:

response.stream.transform(utf8.decoder).listen((value) {
  createdFileName = value;
  print(createdFileName);
});

This part in your function is asynchronous, it uses a callback.

But you don't wait for it to finish in any form. You just continue to return the createdFileName, that by that time most likely has not been filled.

I don't know what your stream looks like, if you only need the first value, you could await that instead of listening:

createdFileName = await  response.stream.transform(utf8.decoder).first;

CodePudding user response:

Replace

 response.stream.transform(utf8.decoder).listen((value) {
      createdFileName = value;
      print(createdFileName);
    });

with

createdFileName=await response.stream.bytesToString();

CodePudding user response:

change code

for (var e in imagefiles) {
           upload(File(e)).then((value) => createdFileNames.add(value));
     }
  • Related