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.
},
),
);
공식 문서
반응형
'플러터' 카테고리의 다른 글
플러터(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 |