[flutter] Flutter Riverpod에서 지하철 정보 앱 만들기
소개
Flutter는 Google에서 개발한 모바일 애플리케이션 개발 플랫폼으로, 다양한 플랫폼에서 작동하는 앱을 만들 수 있습니다. 이번에는 Flutter의 상태 관리 라이브러리 중 하나인 Riverpod를 활용하여 지하철 정보를 보여주는 간단한 앱을 만들어보겠습니다.
Riverpod란?
Riverpod는 Flutter 애플리케이션에서 상태 관리를 위한 라이브러리로, Provider의 개선된 버전입니다. 의존성 주입 및 가시성이 뛰어나며, Immutable State를 제공하여 상태 관리를 용이하게 합니다.
앱 구성
우리가 만들 지하철 정보 앱은 크게 다음과 같은 구성으로 이루어집니다.
- 화면: 역 목록과 선택한 역의 상세 정보가 표시되는 화면
- 데이터: 실제 역 및 노선 정보를 제공하는 API와의 통신
프로젝트 설정
먼저 Flutter 프로젝트를 생성하고, riverpod
및 http
라이브러리를 pubspec.yaml
파일에 추가합니다.
dependencies:
flutter:
sdk: flutter
riverpod: ^1.0.3
http: ^0.14.0
데이터 모델
역과 노선 정보를 표현하기 위한 데이터 모델을 생성합니다.
class Station {
final String name;
final String line;
Station({required this.name, required this.line});
}
API 호출
http
라이브러리를 사용하여 실제 데이터를 호출하는 서비스를 작성합니다.
import 'dart:convert';
import 'package:http/http.dart' as http;
class SubwayService {
Future<List<Station>> fetchStations() async {
final response = await http.get(Uri.parse('https://example.com/stations'));
List<dynamic> data = json.decode(response.body);
return data.map((json) => Station(name: json['name'], line: json['line'])).toList();
}
}
상태 관리
riverpod
를 사용하여 역 및 노선 정보를 상태로 관리합니다.
final stationsProvider = FutureProvider<List<Station>>((ref) async {
final subwayService = SubwayService();
return subwayService.fetchStations();
});
화면 구성
마지막으로 flutter
위젯을 사용하여 화면을 구성하고, 상태를 구독하여 데이터를 표시합니다.
final stations = watch(stationsProvider);
if (stations.when(
loading: () => true,
error: (error, stack) {
return Text('Error: $error');
},
data: (data) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index].name),
subtitle: Text(data[index].line),
);
},
);
}
)) {
return CircularProgressIndicator();
}
위와 같이 간단히 Riverpod
를 활용하여 Flutter에서 지하철 정보 앱을 만들어볼 수 있습니다. Riverpod
의 강력한 상태 관리 및 의존성 주입을 활용하면 복잡한 애플리케이션도 효과적으로 관리할 수 있습니다.