在Flutter中上传文件到Google驱动器时显示进度

insrf1ej  于 2022-12-05  发布在  Flutter
关注(0)|答案(2)|浏览(174)

如何显示进度,文件被上传到谷歌驱动器在Flutter?下面是我的代码,我怎么能重写它,以显示进度的百分比?
不是指进度条,我只是想显示进度百分比。谢谢。

await driveApi.files
            .create(
          fileToUpload,
          supportsAllDrives: true,
          uploadMedia: drive.Media(
            zipFile.openRead(),
            zipFile.lengthSync(),
          ),
        )
            .then((value) async {
          await zipFile.delete();
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('File uploaded successfully'),
            ),
          );
        });
b1uwtaje

b1uwtaje1#

检查这个链接github这显示你可以如何使用它。

osh3o9ms

osh3o9ms2#

您需要修改媒体流以获取块大小,正如您所看到的,我们正在将Steam<List<int>>传递给Media对象,因此需要中断该操作

extension on Stream<List<int>> {
  /// read: callback to print the progress
  /// chunkSize: size of the chunk default is 1024 bytes
  Stream<List<int>> chunkRead(
      {Function(int read)? read, int chunkSize = 1024}) async* {
    final buffer = <int>[];
    var loaded = 0;
    await for (var data in this) {
      buffer.addAll(data);
      for (int i = 0; i < buffer.length; i += chunkSize) {
        data = buffer.sublist(
            i, i + chunkSize > buffer.length ? buffer.length : i + chunkSize);
        loaded += data.length;
        if (read != null) {
          read(loaded);
        }
        yield data;
      }
      buffer.removeRange(0, buffer.length);
    }
  }
}

使用上面的extention来监听Stream。现在我们可以添加自己的函数来处理read value

final options = drive.UploadOptions.resumable;

  uploadMedia: drive.Media(
            zipFile.openRead().chunkRead(
                    chunkSize: options.chunkSize,
                    read: (val) => print("Progress % : ${val*100/zipFile.lengthSync()}"),
                  ),
            zipFile.lengthSync(),
          ),

相关问题