[Flutter] REST API 호출하기 - Dio 패키지

Flutter에서 API를 호출하는 방법은 여러 가지가 있지만, 가장 많이 사용되는 패키지 중 하나가 Dio입니다. Dio는 강력한 기능과 쉬운 사용법을 제공하는 HTTP 클라이언트 패키지로, JSON 데이터 처리, 인터셉터, 오류 처리 등을 효율적으로 관리할 수 있습니다.

이 글에서는 Dio 패키지를 활용한 API 호출 방법을 자세히 설명하겠습니다.

 

 

1. Dio 패키지 설치하기

Flutter 프로젝트에서 Dio를 사용하기 위해 dio install | Dart package 링크를 열어주세요. Installing 페이지가 열리면 flutter pub add dio 우측 아이콘을 눌러서 복사해주세요. 이후, 터미널에서 다음 명령어를 실행하여 패키지를 설치합니다.

flutter pub add dio

 

 

2. Dio 사용법

Dio 객체를 생성하고 기본적인 API 요청을 보내는 방법을 알아보겠습니다.

 

2.1. Dio 객체 생성

Dio를 사용하려면 먼저 Dio 객체를 생성해야 합니다.

import 'package:dio/dio.dart';

final dio = Dio();

 

2.2. GET 요청 보내기

다음은 GET 요청을 보내고 응답을 처리하는 코드입니다.

void fetchData() async {
  try {
    final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
    print(response.data); // 응답 데이터 출력
  } catch (e) {
    print('Error: $e');
  }
}

 

2.3. POST 요청 보내기

POST 요청을 보낼 때는 data 속성에 요청 바디를 포함시켜야 합니다.

void sendData() async {
  try {
    final response = await dio.post(
      'https://jsonplaceholder.typicode.com/posts',
      data: {
        "title": "Flutter Dio",
        "body": "Dio를 활용한 API 호출",
        "userId": 1,
      },
    );
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

 

 

3. 오류 처리 및 예외 처리

API 요청을 보낼 때 예외 처리는 매우 중요합니다. Dio에서는 다양한 예외 유형을 감지할 수 있습니다.

void fetchDataWithErrorHandling() async {
  try {
    final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');
    print(response.data);
  } on DioException catch (e) {
    if (e.type == DioExceptionType.connectionTimeout) {
      print('Connection Timeout!');
    } else if (e.type == DioExceptionType.receiveTimeout) {
      print('Receive Timeout!');
    } else if (e.response != null) {
      print('Error: ${e.response?.statusCode} - ${e.response?.statusMessage}');
    } else {
      print('Unexpected Error: $e');
    }
  }
}