imageDownloadProgress static method

Stream<String> imageDownloadProgress(
  1. String url, {
  2. String imageName = 'myimage',
  3. DownloadLocation location = DownloadLocation.TEMPORARY_DIRECTORY,
})

Implementation

static Stream<String> imageDownloadProgress(String url,
    {String imageName = 'myimage',
    DownloadLocation location =
        DownloadLocation.TEMPORARY_DIRECTORY}) async* {
  StreamController<String> streamController = new StreamController();
  try {
    var dir;
    switch (location) {
      case DownloadLocation.APPLICATION_DIRECTORY:
        dir = await getApplicationSupportDirectory();
        break;
      case DownloadLocation.EXTERNAL_DIRECTORY:
        dir = await getExternalStorageDirectory();
        break;
      case DownloadLocation.TEMPORARY_DIRECTORY:
      default:
        dir = await getTemporaryDirectory();
        break;
    }
    Dio dio = new Dio();
    dio
        .download(
          url,
          "${dir.path}/" + imageName + ".jpeg",
          onReceiveProgress: (int received, int total) {
            streamController
                .add(((received / total) * 100).toStringAsFixed(0) + "%");
          },
        )
        .then((Response response) {})
        .catchError((ex) {
          streamController.add(ex.toString());
        })
        .whenComplete(() {
          streamController.close();
        });
    yield* streamController.stream;
  } catch (ex) {
    throw ex;
  }
}