[flutter] 플러터 build_runner를 사용하여 외부 API 호출하기

플러터(Flutter) 앱을 개발할 때 외부 API를 호출하여 데이터를 가져오는 과정은 매우 일반적입니다. 이를 수행하기 위해 build_runner와 함께 dio 라이브러리를 사용하여 효율적으로 외부 API를 호출하는 방법에 대해 알아보겠습니다.

1. build_runner 및 dio 라이브러리 추가

우선, 프로젝트의 pubspec.yaml 파일에 dio와 build_runner 라이브러리를 추가합니다.

dependencies:
  dio: ^4.0.0

dev_dependencies:
  build_runner: ^2.0.5

그런 다음 터미널에서 다음 명령을 실행하여 라이브러리를 설치합니다.

flutter pub get

2. 외부 API 호출을 위한 모델 클래스 작성

외부 API의 응답과 요청을 표현하는 모델 클래스를 작성합니다. 예를 들어, JSON 응답이 다음과 같은 형식일 경우,

{
  "id": 1,
  "name": "Flutter App"
}

다음과 같은 모델 클래스를 생성합니다.

class AppModel {
  final int id;
  final String name;

  AppModel({required this.id, required this.name});

  factory AppModel.fromJson(Map<String, dynamic> json) {
    return AppModel(
      id: json['id'],
      name: json['name'],
    );
  }
}

3. Dio 및 build_runner 사용

우선 Dio를 사용하여 API를 호출하는 함수를 작성합니다.

import 'package:dio/dio.dart';

class ApiService {
  final Dio _dio = Dio();

  Future<AppModel> fetchData() async {
    final response = await _dio.get('https://api.example.com/data');
    if (response.statusCode == 200) {
      return AppModel.fromJson(response.data);
    } else {
      throw Exception('Failed to load data');
    }
  }
}

다음으로, 이 함수를 호출하여 데이터를 가져오는 클래스를 작성합니다.

import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
import 'app_model.dart';

part 'api_service.g.dart';

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

  @GET("/data")
  Future<AppModel> fetchData();
}

위의 코드에는 Retrofit과 함께 사용되는 api_service.dart 파일이며, build_runner를 사용하여 코드를 생성합니다. 아래의 명령을 실행하여 코드를 생성합니다.

flutter pub run build_runner build

요약

이제 build_runner와 dio를 사용하여 Flutter 앱에서 외부 API를 호출하는 방법에 대해 알아보았습니다. 이를 통해 데이터를 효과적으로 가져와서 앱에 통합할 수 있게 되었습니다.

참조:

이제 효율적으로 API를 사용하여 작업할 수 있게 되었으며, 데이터를 비동기적으로 가져오고 처리하기 위한 준비가 완료되었습니다.