안녕하세요! 이번 포스팅에서는 Flutter와 Firebase를 사용하여 버스 좌석 예약 앱을 만드는 방법에 대해 알아보겠습니다. 이 튜토리얼을 통해 Flutter에서 Firebase Realtime Database를 설정하고, 버스 좌석 예약 기능을 구현하는 방법을 배울 수 있습니다.
단계 1: Flutter 프로젝트 설정
먼저, Flutter 프로젝트를 생성합니다. 터미널에서 다음 명령어를 실행하여 새로운 Flutter 프로젝트를 생성합니다.
flutter create bus_reservation_app
단계 2: Firebase 설정
Firebase 콘솔에서 새로운 프로젝트를 생성합니다. Firebase 콘솔로 이동하여 새 프로젝트를 만들고, 앱의 패키지 이름을 입력합니다.
그 후, 프로젝트 설정으로 이동하여 Firebase를 앱에 추가합니다. google-services.json 파일을 다운로드하고, Flutter 프로젝트의 android/app 폴더에 추가합니다.
단계 3: Firebase Realtime Database 설정
Firebase 콘솔에서 Realtime Database를 활성화합니다. 규칙을 아래와 같이 설정하여 모든 사용자가 데이터를 읽고 쓸 수 있도록 합니다. (프로덕션 앱에서는 권한을 엄격하게 설정해야 합니다.)
{ "rules": { ".read": true, ".write": true } }
단계 4: Flutter 앱에서 예약 기능 구현
Flutter 앱에서 사용자가 버스 좌석을 예약할 수 있는 기능을 구현합니다.
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class BusReservation {
// 예약 기능 클래스
Future<bool> makeReservation(
String busCode, {
required String studentId,
required String date,
required String seatCode,
}) async {
DatabaseReference ref = FirebaseDatabase.instance.ref('busReservation/$busCode');
DataSnapshot snapshot = await ref.once();
Map<dynamic, dynamic>? reservations = snapshot.value;
if (reservations != null) {
for (var reservation in reservations.values) {
if (reservation['student_id'] == studentId) {
return false; // 이미 예약된 학생
}
}
}
await ref.push().set({
'student_id': studentId,
'date': date,
'seatCode': seatCode,
});
return true; // 성공적으로 예약
}
}
단계 5: Flutter UI 구현
Flutter에서 예약할 버스 좌석을 선택할 수 있는 UI를 구현합니다.
import 'package:flutter/material.dart';
class SeatSelectionPage extends StatelessWidget {
final BusReservation busReservation = BusReservation();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('좌석 예약'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
bool success = await busReservation.makeReservation(
'bus001',
studentId: '1901040',
date: '2024-05-03',
seatCode: '1A',
);
if (success) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('예약이 완료되었습니다.'))
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이미 예약된 좌석입니다.'))
);
}
},
child: Text('1A 좌석 예약하기'),
),
),
);
}
}
BusReservation 클래스:
SeatSelectionPage 위젯:
이제 위 코드를 실행하여 버스 좌석 예약 앱을 만들어 보세요! 사용자가 좌석을 선택하고 예약할 때마다 Firebase Realtime Database에 예약 정보가 저장됩니다.
이 튜토리얼에서는 Flutter와 Firebase를 사용하여 간단한 버스 좌석 예약 앱을 만드는 방법을 배웠습니다. Firebase를 사용하면 데이터베이스를 손쉽게 관리하고 실시간으로 데이터를 동기화할 수 있습니다. 추가로 UI를 더욱 멋지게 꾸며보거나 기능을 확장해보세요! 감사합니다.
[Flutter] Hive 활용 팁: 심층 분석 및 실전 가이드 (0) | 2024.05.28 |
---|---|
[Flutter] Provider로 Bookmark 관리하기 (0) | 2024.05.06 |
[Flutter] 앱 만들기 기초: Scaffold 활용 방법 (2) | 2024.04.04 |
[Flutter] Future.wait(다중 비동기 처리) 활용 (0) | 2024.02.02 |
[Flutter] Flexible 위젯 사용법 (0) | 2023.10.05 |