[flutter] Dio를 사용하여 다운로드 진행 상태를 표시하는 방법을 알려주세요.

Dio는 Flutter에서 HTTP 요청을 처리하는 강력하고 유연한 패키지입니다. 다중 파일 다운로드 중에 진행 상태를 표시하는 방법을 살펴보겠습니다.

Dio 패키지 설치

먼저, pubspec.yaml 파일에 Dio 패키지를 추가하세요.

dependencies:
  dio: ^4.0.0

그런 다음 터미널에서 flutter pub get 명령을 실행하여 패키지를 설치하세요.

다운로드 진행 상태 표시하기

이제, Dio를 사용하여 파일을 다운로드하고 진행 상태를 표시하는 방법을 알아봅시다.

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class DownloadProgressWidget extends StatefulWidget {
  @override
  _DownloadProgressWidgetState createState() => _DownloadProgressWidgetState();
}

class _DownloadProgressWidgetState extends State<DownloadProgressWidget> {
  bool _downloading = false;
  double _progress = 0;

  void _startDownload() async {
    Dio dio = Dio();

    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      // 파일 다운로드 요청 설정
      options.responseType = ResponseType.bytes;
      return handler.next(options);
    }, onResponse: (response, handler) {
      // 파일 다운로드 응답 처리
      return handler.next(response);
    }, onProgress: (received, total) {
      // 다운로드 진행 상태 업데이트
      setState(() {
        _downloading = true;
        _progress = (received / total) * 100;
      });
    }));

    // 파일 다운로드
    await dio.download('file_url', '/destination_path');

    setState(() {
      _downloading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('다운로드 진행 상태'),
      ),
      body: Center(
        child: _downloading
            ? CircularProgressIndicator(value: _progress)
            : ElevatedButton(
                onPressed: _startDownload,
                child: Text('파일 다운로드 시작'),
              ),
      ),
    );
  }
}

위 코드에서 _startDownload 메서드는 Dio를 사용하여 파일을 다운로드하고, 진행 상태를 _progress 변수를 통해 업데이트합니다. 이후, 다운로드 상태에 따라 화면에 진행률을 표시하거나 버튼을 표시하는데 사용됩니다.

이제, 다중 파일 다운로드 진행 상태를 Dio를 사용하여 표시하는 기본적인 방법에 대해 알아보았습니다.