Recommand · October 14, 2021 0

Waiting for a stream to complete before the function returns a value

Future<List<Media>> getVideo(var _client, var _videofolder) async {
  final pathContext = path.Context(style:;
  var tempDir = await getTemporaryDirectory();
  String tempPath = tempDir.path;


  final filePath = pathContext.join(tempPath, _videofolder[videoNumber]["name"]);

  if (await io.File(filePath).exists() == false) {
    print("file does not exist yet");
    .fileDownloadFuntion(_videofolder[videoNumber]["id"], _client).then((response) {
      print("file downloaded");
      Uint8List byteList;
      final bytesBuilder = BytesBuilder();
      (response).stream.listen((data) {
      }).onDone(() {
        byteList = bytesBuilder.toBytes();
        final saveFile = io.File(filePath);
        print("File saved at ${saveFile.path}");

        if (io.File(filePath).exists() == true)
            Media.file(io.File(filePath.replaceAll('"', ''))),
    print("file exists");
    if (await io.File(filePath).exists() == true)
        Media.file(io.File(filePath.replaceAll('"', ''))),
  return medias;

The above code looks up for a video file on the local storage. If the file is absent, it proceeds over to download it from google drive. It then saves the downloaded file after converting the file to a 8 bit unsigned integer list.

The problem with the above code is that it returns the unchanged variable medias (a list of Media) before the stream is completed.
I want that the function shouldn’t return a value till the newly downloaded file is added to the list (medias). Is there a way to make this possible?