Jake Seo
제이크서 개발 블로그
Jake Seo
전체 방문자
오늘
어제
  • 분류 전체보기 (719)
    • AI 서비스 개발 일기 (3)
    • LLM 개발 일기 (1)
    • ------레거시 (2025.08.23 이전)--.. (0)
    • 백준 문제풀이 (1)
    • 릿코드 문제풀이 (2)
    • 알고리즘 이론 (10)
      • 기본 이론 (2)
      • 배열과 문자열 (8)
    • 데이터베이스 (15)
      • Planet Scale (1)
      • MSSQL (9)
      • 디비 기본 개념 (1)
      • SQLite 직접 만들어보기 (4)
    • 보안 (7)
    • 설계 (1)
    • 네트워크 (17)
      • HTTP (9)
      • OSI Layers (5)
    • 회고 (31)
      • 연간 회고 (2)
      • 주간 회고 (29)
    • 인프라 (52)
      • 도커 (12)
      • AWS (9)
      • 용어 (21)
      • 웹 성능 (1)
      • 대규모 서비스를 지탱하는 기술 (9)
    • 깃 (7)
    • 빌드 도구 (7)
      • 메이븐 (6)
      • 그레이들 (0)
    • Java (135)
      • 이펙티브 자바 (73)
      • 자바 API (4)
      • 자바 잡지식 (30)
      • 자바 디자인 패턴 (21)
      • 톰캣 (Tomcat) (7)
    • 프레임워크 (64)
      • next.js (14)
      • 스프링 프레임워크 (28)
      • 토비의 스프링 (6)
      • 스프링 부트 (3)
      • JPA (Java Persistence API) (5)
      • Nest.js (8)
    • 프론트엔드 (48)
      • 다크모드 (1)
      • 노드 패키지 관리 매니저 (3)
      • CSS (19)
      • Web API (11)
      • tailwind-css (1)
      • React (5)
      • React 새 공식문서 요약 (1)
      • HTML (Markup Language) (5)
    • 자바스크립트 (108)
      • 모던 자바스크립트 (31)
      • 개념 (31)
      • 정규표현식 (5)
      • 코드 스니펫 (1)
      • 라이브러리 (6)
      • 인터뷰 (24)
      • 웹개발자를 위한 자바스크립트의 모든 것 (6)
      • 팁 (2)
    • Typescript (49)
    • 리눅스와 유닉스 (10)
    • Computer Science (1)
      • Compiler (1)
    • IDE (3)
      • VSCODE (1)
      • IntelliJ (2)
    • 세미나 & 컨퍼런스 (1)
    • 용어 (개발용어) (16)
      • 함수형 프로그래밍 용어들 (1)
    • ORM (2)
      • Prisma (2)
    • NODEJS (2)
    • cypress (1)
    • 리액트 네이티브 (React Native) (31)
    • 러스트 (Rust) (15)
    • 코틀린 (Kotlin) (4)
      • 자바에서 코틀린으로 (4)
    • 정규표현식 (3)
    • 구글 애널리틱스 (GA) (1)
    • SEO (2)
    • UML (2)
    • 맛탐험 (2)
    • 리팩토링 (1)
    • 서평 (2)
    • 소프트웨어 공학 (18)
      • 테스팅 (16)
      • 개발 프로세스 (1)
    • 교육학 (1)
    • 삶의 지혜, 통찰 (1)
    • Chat GPT (2)
    • 쉘스크립트 (1)
    • 컴파일 (2)
    • Dart (12)
    • 코드팩토리의 플러터 프로그래밍 (4)
    • 플러터 (17)
    • 안드로이드 스튜디오 (1)
    • 윈도우즈 (1)
    • 잡다한 백엔드 지식 (1)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 러스트
  • Java
  • 도커공식문서
  • 메이븐 페이즈
  • 프로그래머의 뇌
  • 이펙티브 자바 item9
  • item8
  • 싱글톤 패턴
  • 자바 검증
  • try-with-resources
  • 서버리스 컴퓨팅
  • prerendering
  • 싱글턴
  • 디자인패턴
  • 참조 해제
  • 이펙티브 자바
  • rust
  • 이펙티브자바
  • 팩터리 메서드 패턴
  • 싱글톤
  • 추상 팩터리 패턴
  • 자바
  • 메이븐 골
  • Javadoc 자바독 자바주석 주석 Comment
  • 느린 쿼리
  • 작업기억공간
  • 알고리즘
  • item7
  • item9
  • 자바스크립트
  • 빈 검증
  • 자바스크립트 면접
  • Next.js
  • pnpm
  • NEXT JS
  • 자바스크립트 인터뷰
  • bean Validation
  • MSSQL
  • 플라이웨이트패턴
  • serverless computing
  • 객체복사
  • 스프링 검증
  • Pre-rendering
  • 슬로우 쿼리
  • 외래키 제약조건
  • 메이븐 라이프사이클
  • 토비의 스프링
  • 자바 디자인패턴
  • 자료구조
  • next js app

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Jake Seo

제이크서 개발 블로그

플러터

Flutter Dio 라이브러리란?

2023. 11. 11. 15:29

Dio 라이브러리란?

  • Flutter 프레임워크 환경에서 HTTP 요청을 할 때 유용하게 쓰이는 라이브러리이다.
  • 웹에서 쓰는 범용 Fetch 라이브러리들과 비슷한 기능을 제공한다.
    • Global configuration
    • Interceptors
    • FormData
    • Request cancellation
    • File uploading/downloading
    • Timeout
    • Custom adapters
    • Transformer

기본 사용법

import 'package:dio/dio.dart';

final dio = Dio();

void request() async {
  Response response;
  response = await dio.get('/test?id=12&name=dio');
  print(response.data.toString());
  // The below request is the same as above.
  response = await dio.get(
    '/test',
    queryParameters: {'id': 12, 'name': 'dio'},
  );
  print(response.data.toString());
}

요청 옵션

/// Http method.
String method;

/// Request base url, it can contain sub path, like: https://dart.dev/api/.
String? baseUrl;

/// Http request headers.
Map<String, dynamic>? headers;

/// Timeout for opening url.
Duration? connectTimeout;

/// Whenever more than [receiveTimeout] passes between two events from response stream,
/// [Dio] will throw the [DioException] with [DioExceptionType.RECEIVE_TIMEOUT].
/// Note: This is not the receiving time limitation.
Duration? receiveTimeout;

/// Request data, can be any type.
dynamic data;

/// If the `path` starts with 'http(s)', the `baseURL` will be ignored, otherwise,
/// it will be combined and then resolved with the baseUrl.
String path;

/// The request Content-Type.
///
/// The default `content-type` for requests will be implied by the
/// [ImplyContentTypeInterceptor] according to the type of the request payload.
/// The interceptor can be removed by
/// [Interceptors.removeImplyContentTypeInterceptor].
///
/// If you want to encode request body with 'application/x-www-form-urlencoded',
/// you can set [Headers.formUrlEncodedContentType], and [Dio]
/// will automatically encode the request body.
String? contentType;

/// [responseType] indicates the type of data that the server will respond with
/// options which defined in [ResponseType] are `json`, `stream`, `plain`.
///
/// The default value is `json`, dio will parse response string to json object automatically
/// when the content-type of response is 'application/json'.
///
/// If you want to receive response data with binary bytes, for example,
/// downloading a image, use `stream`.
///
/// If you want to receive the response data with String, use `plain`.
ResponseType? responseType;

/// `validateStatus` defines whether the request is successful for a given
/// HTTP response status code. If `validateStatus` returns `true` ,
/// the request will be perceived as successful; otherwise, considered as failed.
ValidateStatus? validateStatus;

/// Custom field that you can retrieve it later in [Interceptor],
/// [Transformer] and the [Response.requestOptions] object.
Map<String, dynamic>? extra;

/// Common query parameters.
Map<String, dynamic /*String|Iterable<String>*/ >? queryParameters;

/// [listFormat] indicates the format of collection data in request options。
/// The default value is `multiCompatible`
ListFormat? listFormat;

응답

/// Response body. may have been transformed, please refer to [ResponseType].
T? data;

/// The corresponding request info.
RequestOptions requestOptions;

/// HTTP status code.
int? statusCode;

/// Returns the reason phrase associated with the status code.
/// The reason phrase must be set before the body is written
/// to. Setting the reason phrase after writing to the body.
String? statusMessage;

/// Whether this response is a redirect.
/// ** Attention **: Whether this field is available depends on whether the
/// implementation of the adapter supports it or not.
bool isRedirect;

/// The series of redirects this connection has been through. The list will be
/// empty if no redirects were followed. [redirects] will be updated both
/// in the case of an automatic and a manual redirect.
///
/// ** Attention **: Whether this field is available depends on whether the
/// implementation of the adapter supports it or not.
List<RedirectRecord> redirects;

/// Custom fields that only for the [Response].
Map<String, dynamic> extra;

/// Response headers.
Headers headers;

여러 요청을 한번에 하고 싶을 때

response = await Future.wait([dio.post('/info'), dio.get('/token')]);

파일을 다운로드 받을 때

response = await dio.download(
  'https://pub.dev/',
  (await getTemporaryDirectory()).path + 'pub.html',
);

응답 스트림을 받을 때

final rs = await dio.get(
  url,
  options: Options(responseType: ResponseType.stream), // Set the response type to `stream`.
);

print(rs.data.stream); // Response stream.

bytes 로 응답을 받을 때

final rs = await Dio().get<List<int>>(
  url,
  options: Options(responseType: ResponseType.bytes), // Set the response type to `bytes`.
);

print(rs.data); // Type: List<int>.

FormData 를 보내야 할 때

final formData = FormData.fromMap({
  'name': 'dio',
  'date': DateTime.now().toIso8601String(),
});

final response = await dio.post('/info', data: formData);

여러 파일을 업로드할 때

final formData = FormData.fromMap({
  'name': 'dio',
  'date': DateTime.now().toIso8601String(),
  'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
  'files': [
    await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'),
    await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'),
  ]
});

final response = await dio.post('/info', data: formData);

업로드 진행상황을 리스닝할 때

final response = await dio.post(
  'https://www.dtworkroom.com/doris/1/2.0.0/test',
  data: {'aa': 'bb' * 22},
  onSendProgress: (int sent, int total) {
    print('$sent $total');
  },
);

바이너리 데이터를 스트림으로 보낼 때

// Binary data
final postData = <int>[0, 1, 2];
await dio.post(
  url,
  data: Stream.fromIterable(postData.map((e) => [e])), // Creates a Stream<List<int>>.
  options: Options(
    headers: {
      Headers.contentLengthHeader: postData.length, // Set the content-length.
    },
  ),
);

공식 문서

https://pub.dev/packages/dio

저작자표시 비영리 (새창열림)

'플러터' 카테고리의 다른 글

플러터(Flutter) 의 RefreshIndicator 란?  (5) 2023.11.12
플러터(Flutter) 의 FutureBuilder 란?  (0) 2023.11.11
플러터(Flutter) 의 컨트롤러 (Controller) 란?  (0) 2023.11.11
플러터 ListView 에서 사용되는 옵션들 간단하게 정리  (2) 2023.11.11
플러터의 상호작용 중 제스처(Gesture) 란?  (1) 2023.10.29
    '플러터' 카테고리의 다른 글
    • 플러터(Flutter) 의 FutureBuilder 란?
    • 플러터(Flutter) 의 컨트롤러 (Controller) 란?
    • 플러터 ListView 에서 사용되는 옵션들 간단하게 정리
    • 플러터의 상호작용 중 제스처(Gesture) 란?
    Jake Seo
    Jake Seo
    ✔ 댓글로 틀린 부분을 지적해주시면 기분 나빠하지 않고 수정합니다. ✔ 많은 퇴고를 거친 글이 좋은 글이 된다고 생각합니다. ✔ 간결하고 명료하게 사람들을 이해 시키는 것을 목표로 합니다.

    티스토리툴바