download method Null safety

Future<File> download(
  1. SpeechPackage pack
)

Download a speech pack

Adapted from: https://bit.ly/3iYONOK

Implementation

Future<File> download(SpeechPackage pack) async {
  // Set language being downloaded
  downloadProgress(downloadProgress.value.copyWith(language: pack.lang));

  // Start downloading
  final request = Request('GET', Uri.parse(pack.url));
  final StreamedResponse response = await Client().send(request);

  /// Get file size
  final contentLength = response.contentLength ?? 0;

  // Get file to download to
  final file =
      await _getFile('$speechDirectory/${pack.lang}_${pack.version}.zip');

  // If the file downloaded in full
  if (file.existsSync() && file.lengthSync() == contentLength) {
    Future.delayed(
      Duration.zero,
      () => _speechPackWorkflow.changeState(SpeechPackState.downloadComplete),
    );
  }
  // file not fully downloaded
  else {
    file.createSync(recursive: true);
    _speechPackWorkflow.changeState(SpeechPackState.downloading);
    // Download data to the file
    List<int> bytes = [];
    final stream = response.stream.listen(
      /// Update [downloadProgress]
      (List<int> newBytes) {
        bytes.addAll(newBytes);
        final downloadedLength = bytes.length;
        if (contentLength != 0) {
          updateProgress(downloadedLength / contentLength);
        }
      },

      /// Save data to file when done
      onDone: () {
        updateProgress(0);
        file.writeAsBytesSync(bytes, flush: true);
        _speechPackWorkflow.changeState(SpeechPackState.downloadComplete);
      },

      /// Indicate error
      onError: (e) {
        _speechPackWorkflow.changeState(SpeechPackState.downloadError);
      },
      cancelOnError: true,
    );

    // Add stream to downloadProgress
    downloadProgress(downloadProgress.value.copyWith(stream: stream));
  }

  return file;
}