[dart] HTTP 요청 중에 진행 상황 표시하기

다음은 Dart에서 HTTP 요청 중에 진행 상황을 표시하는 간단한 예제입니다.

먼저, http 패키지를 가져옵니다.

import 'package:http/http.dart' as http;

다음으로, 진행 상황을 표시할 때 사용할 함수를 정의합니다.

void showProgress(int sent, int total) {
  double percentage = (sent / total) * 100;
  print('Progress: ${percentage.toStringAsFixed(2)}%');
}

이제 HTTP 요청을 보낼 때 진행 상황을 표시할 수 있는 Stream을 생성합니다.

void main() async {
  var url = Uri.parse('https://api.example.com/data');
  var request = http.Request('POST', url);
  request.body = 'Hello, Server';
  request.send().then((http.StreamedResponse response) {
    if (response.statusCode == 200) {
      print('Request sent successfully');
    }
  }).asStream().listen((http.StreamedHttpMessage msg) {
    msg.stream.listen((List<int> chunk) {
      showProgress(chunk.length, request.contentLength);
      // 여기에서 chunk를 처리합니다.
    });
  });
}

위의 코드는 HTTP 요청을 보내고 응답을 받을 때까지의 진행 상황을 표시하는 방법을 보여줍니다. showProgress 함수를 사용하여 데이터를 보내고 받을 때의 진행률을 출력합니다.

이렇게 하면 사용자는 HTTP 요청이 진행 중임을 알고, 상호작용이 필요한 경우 기다릴 수 있습니다.

더 자세한 내용은 Dart HTTP 패키지 문서를 참조하십시오.