imageDownloadProgress method

  1. @override
Stream<String> imageDownloadProgress(
  1. String url, {
  2. String imageName = 'myimage',
  3. ImageFormat fileExtension = ImageFormat.jpeg,
  4. DownloadLocation location = DownloadLocation.temporaryDirectory,
})
override

before using homeScreen, lockScreen , bothScreen, systemScreen . we need to download image . imageName -> after downloading image name to be saved so when using home screen, etc we can pass this name and location location where the image is downloaded

Implementation

@override
Stream<String> imageDownloadProgress(
  String url, {
  String imageName = 'myimage',
  ImageFormat fileExtension = ImageFormat.jpeg,
  DownloadLocation location = DownloadLocation.temporaryDirectory,
}) {
  final streamController = StreamController<String>();

  (() async {
    try {
      Directory dir;
      switch (location) {
        case DownloadLocation.applicationDirectory:
          dir = await getApplicationSupportDirectory();
          break;
        case DownloadLocation.externalDirectory:
          final externalDir = await getExternalStorageDirectory();
          if (externalDir == null) {
            throw Exception("External dir not available");
          }
          dir = externalDir;
          break;
        default:
          dir = await getTemporaryDirectory();
      }

      final ext = _imageFormatToExtension(fileExtension);
      final filePath = "${dir.path}/$imageName.$ext";

      final receivePort = ReceivePort();

      // Spawn isolate
      await Isolate.spawn(
        _downloadImageWithProgress,
        DownloadParams(url, filePath, receivePort.sendPort),
      );

      receivePort.listen((msg) {
        if (msg == "done") {
          streamController.close();
          receivePort.close();
        } else if (msg.toString().startsWith("error:")) {
          streamController.addError(msg);
          streamController.close();
          receivePort.close();
        } else {
          streamController.add(msg); // <--- progress update (e.g., "45%")
        }
      });
    } catch (e) {
      streamController.addError("Failed: ${e.toString()}");
      streamController.close();
    }
  })();

  return streamController.stream;
}