[flutter] Dio를 사용하여 파일 다운로드를 중단하는 방법을 알려주세요.

먼저 Dio 패키지를 이용하여 파일을 다운로드하는 코드를 작성하겠습니다.

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

void downloadFile() async {
  Dio dio = Dio();
  String url = "https://example.com/file.zip";
  String savePath = await getFilePath();
  
  await dio.download(
    url,
    savePath,
    onReceiveProgress: (received, total) {
      print((received / total * 100).toStringAsFixed(0) + "%");
    }
  );
}

Future<String> getFilePath() async {
  Directory appDocDir = await getApplicationDocumentsDirectory();
  String appDocPath = appDocDir.path;
  return appDocPath + "/file.zip";
}

이제, 파일 다운로드를 중단하는 방법을 알아보겠습니다.

CancelToken cancelToken = CancelToken();
dio.download(
  url,
  savePath,
  cancelToken: cancelToken,
  onReceiveProgress: (received, total) {
    // 파일 다운로드 중인 프로그레스를 받아올 수 있습니다.
  }
);

// 다운로드를 중단하고 싶을 때
cancelToken.cancel("사용자가 다운로드를 중단했습니다.");

이렇게하면 Dio를 사용하여 파일 다운로드를 중단할 수 있습니다.

참고 자료: