본문 바로가기
Flutter/Package

플러터에서 Retrofit 패키지 사용하기 [AIP]

by Maccrey Coding 2024. 7. 13.
반응형

안녕하세요! 오늘은 플러터(Flutter)에서 Retrofit 패키지를 사용하여 네트워크 요청을 처리하는 방법과 몇 가지 유용한 옵션에 대해 알아보겠습니다.

Retrofit은 코드 생성을 통해 API 요청을 간편하게 만들어주는 패키지입니다.

Dio 패키지를 기반으로 하고 있습니다.

1. Retrofit 패키지 설치하기

먼저, pubspec.yaml 파일에 Retrofit과 Dio 패키지를 추가해야 합니다.

dependencies:
  dio: ^4.0.0
  retrofit: ^4.0.0

dev_dependencies:
  retrofit_generator: ^4.0.0
  build_runner: ^2.0.0

파일을 저장한 후, 터미널에서 flutter pub get 명령어를 실행해 패키지를 설치합니다.

2. API 인터페이스 정의하기

Retrofit은 API 인터페이스를 정의하여 네트워크 요청을 처리합니다. 먼저, API 인터페이스를 정의합니다.

import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
import 'models/post.dart'; // Post 모델을 정의했다고 가정

part 'api_service.g.dart';

@RestApi(baseUrl: "https://jsonplaceholder.typicode.com")
abstract class ApiService {
  factory ApiService(Dio dio, {String baseUrl}) = _ApiService;

  @GET("/posts/{id}")
  Future<Post> getPost(@Path("id") int id);

  @POST("/posts")
  Future<Post> createPost(@Body() Post post);
}

이 코드에서 @RestApi 어노테이션을 사용하여 API의 기본 URL을 설정하고, @GET과 @POST 어노테이션을 사용하여 각각 GET 요청과 POST 요청을 정의합니다.

3. 모델 클래스 정의하기

API 응답을 매핑하기 위한 모델 클래스를 정의합니다. 여기서는 Post 모델 클래스를 예로 들어보겠습니다.

import 'package:json_annotation/json_annotation.dart';

part 'post.g.dart';

@JsonSerializable()
class Post {
  int userId;
  int id;
  String title;
  String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);

  Map<String, dynamic> toJson() => _$PostToJson(this);
}

4. 코드 생성하기

터미널에서 build_runner를 사용하여 코드를 생성합니다.

flutter pub run build_runner build

이 명령어를 실행하면 Retrofit이 자동으로 필요한 코드를 생성합니다.

5. API 호출하기

이제 API를 호출할 준비가 되었습니다. 다음은 API를 호출하는 예제입니다.

import 'package:dio/dio.dart';
import 'api_service.dart';
import 'models/post.dart';

void main() async {
  final dio = Dio();
  final apiService = ApiService(dio);

  try {
    // GET 요청 예제
    final post = await apiService.getPost(1);
    print('Post Title: ${post.title}');

    // POST 요청 예제
    final newPost = Post(userId: 1, id: 0, title: 'New Post', body: 'This is the body');
    final createdPost = await apiService.createPost(newPost);
    print('Created Post ID: ${createdPost.id}');
  } catch (e) {
    print('Error: $e');
  }
}

이 코드에서 ApiService 객체를 생성하고, getPost 및 createPost 메서드를 호출하여 각각 GET 및 POST 요청을 보냅니다.

6. 옵션 설정하기

Dio와 마찬가지로 다양한 옵션을 설정할 수 있습니다. 예를 들어, timeout 설정을 해보겠습니다.

final dio = Dio(BaseOptions(
  connectTimeout: 5000,
  receiveTimeout: 3000,
));
final apiService = ApiService(dio);

이렇게 하면 연결 시간 초과와 응답 시간 초과를 설정할 수 있습니다.

마무리

이렇게 해서 플러터에서 Retrofit 패키지를 사용하는 방법과 몇 가지 유용한 옵션에 대해 알아보았습니다. Retrofit을 사용하면 네트워크 요청을 매우 간편하게 처리할 수 있습니다. 더 많은 기능과 옵션은 Retrofit 공식 문서를 참고하세요.

행복한 코딩 되세요!

반응형