일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- buildcontext
- GetX
- guideline 4.3(a)
- withopacity
- flutter_secure_storage
- permissiondeniedexception
- flutter doctor -v
- providernotfoundexception
- exception
- 에러
- information needed
- .dio
- 채팅 메시지 정렬
- youtube_player_flutter
- pub.dev
- Flutter
- appstroe connect guideline
- dart sdk version upgrade
- guideline 1.5
- exception caught by image resource service
- app store connect guideline
- 플러터
- app completeness
- tflite_flutter
- AI
- undefined name
- app stroe connect guideline
- appstore connect guideline
- flutter_dotenv
- infinity or nan toint
Archives
- Today
- Total
min_chan님의 블로그
[pub.dev] - dio 본문
dio란?
Dio는 강력한 기능과 편리한 사용성으로 많은 개발자들에게 사랑받고 있는 http 패키지다.
- 글로벌 설정 가능
- 인터셉터 지원 (요청/응답 변조 가능)
- FormData 지원 (파일 업로드 용이)
- 요청 취소 가능
- 다운로드 및 업로드 진행 상태 확인
- 요청 및 응답 변환 (Transformers)
- 커스텀 어댑터 지원
dio 사용법
1. 패키지 설치
- 터미널에서 pub add 명령어를 실행해 패키지를 설치
2. get 요청
- Dio 인스턴스를 생성하면, 이후 get(), post(), put(), delete() 등의 요청을 쉽게 수행할 수 있다.
import 'package:dio/dio.dart';
final dio = Dio();
void getHttp() async {
final response = await dio.get('https://dart.dev');
print(response);
}
2.1 쿼리 파라미터 추가
Future<void> getWithQueryParams() async {
Response response = await dio.get(
'https://jsonplaceholder.typicode.com/posts',
queryParameters: {'userId': 1},
);
print(response.data);
}
3. post 요청
Future<void> postRequest() async {
Response response = await dio.post(
'https://jsonplaceholder.typicode.com/posts',
data: {'title': 'Dio 테스트', 'body': 'Flutter Dio 사용법', 'userId': 1},
);
print(response.data);
}
3.1 동시 처리 요청
Future<void> multipleRequests() async {
List<Response> responses = await Future.wait([
dio.get('https://jsonplaceholder.typicode.com/posts/1'),
dio.get('https://jsonplaceholder.typicode.com/posts/2')
]);
print(responses[0].data);
print(responses[1].data);
}
4. 파일 다운로드
import 'package:path_provider/path_provider.dart';
Future<void> downloadFile() async {
final directory = await getTemporaryDirectory();
final filePath = '${directory.path}/downloaded_file.txt';
await dio.download(
'https://example.com/file.txt',
filePath,
onReceiveProgress: (received, total) {
print('Download progress: ${(received / total * 100).toStringAsFixed(0)}%');
},
);
print('Download completed: $filePath');
}
5. interceptors
- 각 dio 인스턴스마다 하나 이상의 인터셉터를 추가하여 요청, 응답 및 오류가 그때까지 처리되기 전에 인터셉터를 하거나 catchError를 할 수 있다.
import 'package:dio/dio.dart';
class CustomInterceptors extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print('REQUEST[${options.method}] => PATH: ${options.path}');
super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
super.onResponse(response, handler);
}
@override
Future onError(DioException err, ErrorInterceptorHandler handler) async {
print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
super.onError(err, handler);
}
}
'pub.dev' 카테고리의 다른 글
[pub.dev] - intl (0) | 2025.03.17 |
---|---|
[pub.dev] - http (0) | 2025.03.13 |
[pub.dev] - flutter_secure_storage (0) | 2025.03.05 |
[pub.dev] - flutter_dotenv (0) | 2025.02.27 |
[pub.dev] - provider (0) | 2025.02.24 |