372 lines
13 KiB
Dart
372 lines
13 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'dart:convert';
|
|
import 'dart:async'; // Timer를 사용하기 위해 추가
|
|
import 'package:intl/intl.dart';
|
|
import 'package:csp2/common/widgets/upcoming_class_card.dart';
|
|
// import 'package:flutter_native_timezone/flutter_native_timezone.dart'; // 주석 처리된 상태 유지
|
|
import '../plan_page.dart'; // PlanPage import
|
|
|
|
// CaseStudyPlan 클래스 (변경 없음)
|
|
class CaseStudyPlan {
|
|
final String planId;
|
|
final String planTitle;
|
|
final String planTeacher;
|
|
final String thumbnail;
|
|
|
|
CaseStudyPlan({
|
|
required this.planId,
|
|
required this.planTitle,
|
|
required this.planTeacher,
|
|
required this.thumbnail,
|
|
});
|
|
|
|
factory CaseStudyPlan.fromJson(Map<String, dynamic> json) {
|
|
return CaseStudyPlan(
|
|
planId: json['casestudy lesson id'] ?? '아이디 없음',
|
|
planTitle: json['course_name'] ?? '제목 없음',
|
|
planTeacher: json['planTeacher'] ?? '선생님',
|
|
thumbnail: json['course_thumbnail'] ?? '',
|
|
);
|
|
}
|
|
}
|
|
|
|
// 새로운 추천 플랜 모델
|
|
class RecommendPlan {
|
|
final String planId;
|
|
final String planName;
|
|
final String thumbnail;
|
|
|
|
RecommendPlan({
|
|
required this.planId,
|
|
required this.planName,
|
|
required this.thumbnail,
|
|
});
|
|
|
|
factory RecommendPlan.fromJson(Map<String, dynamic> json) {
|
|
return RecommendPlan(
|
|
planId: json['plan id'] ?? 'ID 없음',
|
|
planName: json['plane name'] ?? '이름 없음',
|
|
thumbnail: json['thumbnail'] ?? '',
|
|
);
|
|
}
|
|
}
|
|
|
|
typedef OnNavigateToPage = void Function(int pageIndex);
|
|
|
|
class HomePage extends StatefulWidget {
|
|
// *** 추가: 콜백 함수를 받을 프로퍼티 ***
|
|
final OnNavigateToPage onNavigateToPlanTab;
|
|
|
|
const HomePage({
|
|
super.key,
|
|
required this.onNavigateToPlanTab, // *** 생성자에서 콜백 함수를 받도록 수정 ***
|
|
});
|
|
|
|
@override
|
|
State<HomePage> createState() => _HomePageState();
|
|
}
|
|
|
|
class _HomePageState extends State<HomePage> {
|
|
late Future<List<CaseStudyPlan>> _caseStudyPlans;
|
|
DateTime _currentTime = DateTime.now();
|
|
String _currentTimeZone = 'Loading timezone...';
|
|
late Stream<DateTime> _clockStream;
|
|
|
|
// --- 추천 클래스 관련 상태 변수 ---
|
|
List<RecommendPlan> _recommendPlans = [];
|
|
int _currentRecommendIndex = 0;
|
|
Timer? _recommendTimer;
|
|
bool _isLoadingRecommends = true;
|
|
bool _hasRecommendError = false;
|
|
String _recommendErrorText = '';
|
|
// --- 추천 클래스 관련 상태 변수 끝 ---
|
|
|
|
List<Widget> _buildPageContents() {
|
|
return [
|
|
_buildHomeContent(),
|
|
const PlanPage(),
|
|
];
|
|
}
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_caseStudyPlans = _fetchCaseStudyPlans();
|
|
_fetchTimezone();
|
|
_clockStream = Stream.periodic(const Duration(seconds: 1), (_) {
|
|
return DateTime.now();
|
|
});
|
|
_currentTime = DateTime.now();
|
|
|
|
// --- 추천 클래스 데이터 로드 및 타이머 시작 ---
|
|
_fetchRecommendPlans();
|
|
// --- 추천 클래스 데이터 로드 및 타이머 시작 끝 ---
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_recommendTimer?.cancel(); // 위젯 제거 시 타이머 취소
|
|
super.dispose();
|
|
}
|
|
|
|
Future<List<CaseStudyPlan>> _fetchCaseStudyPlans() async {
|
|
final response = await http
|
|
.get(Uri.parse('https://helloworld2-ad2uqhckxq-uc.a.run.app'));
|
|
if (response.statusCode == 200) {
|
|
final Map<String, dynamic> decodedJson = json.decode(response.body);
|
|
if (decodedJson.containsKey('data') && decodedJson['data'] is List) {
|
|
final List<dynamic> plansJson = decodedJson['data'];
|
|
return plansJson
|
|
.map((jsonItem) =>
|
|
CaseStudyPlan.fromJson(jsonItem as Map<String, dynamic>))
|
|
.toList();
|
|
} else {
|
|
throw Exception(
|
|
'Invalid data format: "data" field is missing or not a list.');
|
|
}
|
|
} else {
|
|
throw Exception(
|
|
'Failed to load case study plans. Status Code: ${response.statusCode}');
|
|
}
|
|
}
|
|
|
|
Future<void> _fetchTimezone() async {
|
|
try {
|
|
final String timeZone = DateTime.now().timeZoneName;
|
|
if (mounted) {
|
|
setState(() {
|
|
_currentTimeZone = timeZone;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_currentTimeZone = 'Failed to get timezone.';
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- 추천 클래스 데이터 가져오는 함수 ---
|
|
Future<void> _fetchRecommendPlans() async {
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_isLoadingRecommends = true;
|
|
_hasRecommendError = false;
|
|
_recommendErrorText = '';
|
|
});
|
|
try {
|
|
final response = await http
|
|
.get(Uri.parse('https://helloworld3-ad2uqhckxq-uc.a.run.app'));
|
|
if (!mounted) return;
|
|
|
|
if (response.statusCode == 200) {
|
|
final Map<String, dynamic> decodedJson = json.decode(response.body);
|
|
if (decodedJson.containsKey('data') && decodedJson['data'] is List) {
|
|
final List<dynamic> plansJson = decodedJson['data'];
|
|
setState(() {
|
|
_recommendPlans = plansJson
|
|
.map((jsonItem) =>
|
|
RecommendPlan.fromJson(jsonItem as Map<String, dynamic>))
|
|
.toList();
|
|
_isLoadingRecommends = false;
|
|
if (_recommendPlans.isNotEmpty) {
|
|
_currentRecommendIndex = 0; // 데이터 로드 후 인덱스 초기화
|
|
_startRecommendTimer(); // 데이터 로드 후 타이머 시작
|
|
}
|
|
});
|
|
} else {
|
|
throw Exception('Invalid data format for recommend plans: "data" field is missing or not a list.');
|
|
}
|
|
} else {
|
|
throw Exception(
|
|
'Failed to load recommend plans. Status Code: ${response.statusCode}');
|
|
}
|
|
} catch (e) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_isLoadingRecommends = false;
|
|
_hasRecommendError = true;
|
|
_recommendErrorText = e.toString();
|
|
});
|
|
}
|
|
}
|
|
}
|
|
// --- 추천 클래스 데이터 가져오는 함수 끝 ---
|
|
|
|
// --- 추천 클래스 순환 타이머 시작 함수 ---
|
|
void _startRecommendTimer() {
|
|
_recommendTimer?.cancel();
|
|
if (_recommendPlans.isEmpty || !mounted) return;
|
|
|
|
_recommendTimer = Timer.periodic(const Duration(seconds: 10), (timer) {
|
|
if (!mounted || _recommendPlans.isEmpty) {
|
|
timer.cancel();
|
|
return;
|
|
}
|
|
setState(() {
|
|
_currentRecommendIndex = (_currentRecommendIndex + 1) % _recommendPlans.length;
|
|
});
|
|
});
|
|
}
|
|
// --- 추천 클래스 순환 타이머 시작 함수 끝 ---
|
|
|
|
Widget _buildLocalTimeBar() {
|
|
return StreamBuilder<DateTime>(
|
|
stream: _clockStream,
|
|
initialData: _currentTime,
|
|
builder: (context, snapshot) {
|
|
final DateTime displayTime = snapshot.data ?? DateTime.now();
|
|
final String formattedDate = DateFormat.yMMMMd().format(displayTime);
|
|
final String formattedTime = DateFormat.jms().format(displayTime);
|
|
return Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
|
|
decoration: BoxDecoration(
|
|
color: Theme.of(context).primaryColor.withAlpha(25),
|
|
borderRadius: BorderRadius.circular(8.0),
|
|
),
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center, // 세로 중앙 정렬
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text('Your Local Time', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0)),
|
|
const SizedBox(height: 6.0),
|
|
Text('$formattedTime', style: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500)),
|
|
// const SizedBox(height: 4.0),
|
|
// Text('Timezone: $_currentTimeZone', style: TextStyle(fontSize: 13.0, color: Colors.grey[700])),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
Widget _buildButtons() {
|
|
return Column(
|
|
mainAxisAlignment: MainAxisAlignment.center, // 세로 중앙 정렬
|
|
crossAxisAlignment: CrossAxisAlignment.stretch, // 버튼이 가로로 꽉 차게 설정
|
|
children: [
|
|
Expanded( // 버튼이 할당된 세로 공간을 모두 차지하도록 설정
|
|
child: ElevatedButton.icon(
|
|
icon: const Icon(Icons.add_circle_outline, size: 20),
|
|
label: const Text('Book Class', style: TextStyle(fontSize: 20)),
|
|
onPressed: () {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Book Class 버튼 기능 구현 예정')),
|
|
);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.blue, // 배경색을 파란색으로 설정
|
|
foregroundColor: Colors.white, // 글자색을 흰색으로 설정
|
|
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(8.0),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
// const SizedBox(height: 8.0),
|
|
// ElevatedButton.icon(
|
|
// icon: const Icon(Icons.schedule, size: 20),
|
|
// label: const Text('Schedule', style: TextStyle(fontSize: 14)),
|
|
// onPressed: () {
|
|
// ScaffoldMessenger.of(context).showSnackBar(
|
|
// const SnackBar(content: Text('Schedule 버튼 기능 구현 예정')),
|
|
// );
|
|
// },
|
|
// style: ElevatedButton.styleFrom(
|
|
// padding: const EdgeInsets.symmetric(vertical: 12.0),
|
|
// shape: RoundedRectangleBorder(
|
|
// borderRadius: BorderRadius.circular(8.0),
|
|
// ),
|
|
// ),
|
|
// ),
|
|
],
|
|
);
|
|
}
|
|
|
|
Widget _buildHomeContent() {
|
|
return Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: <Widget>[
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
|
|
child: IntrinsicHeight(
|
|
child: Row(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Expanded(
|
|
flex: 1,
|
|
child: _buildLocalTimeBar(),
|
|
),
|
|
const SizedBox(width: 12.0),
|
|
Expanded(
|
|
flex: 1,
|
|
child: _buildButtons(),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
const Padding(
|
|
padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 8.0), // vertical을 위아래 다르게 조정
|
|
child: Text('Upcoming Classes', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),
|
|
),
|
|
SizedBox(
|
|
height: 250, // 가로 리스트의 높이를 지정합니다.
|
|
child: FutureBuilder<List<CaseStudyPlan>>(
|
|
future: _caseStudyPlans,
|
|
builder: (context, snapshot) {
|
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
} else if (snapshot.hasError) {
|
|
return Center(child: Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Text('Error loading upcoming classes: ${snapshot.error}', textAlign: TextAlign.center),
|
|
));
|
|
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
|
return const Center(child: Text('No upcoming classes available.'));
|
|
} else {
|
|
final plans = snapshot.data!;
|
|
return ListView.builder(
|
|
scrollDirection: Axis.horizontal, // 가로 스크롤로 변경
|
|
padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0),
|
|
itemCount: plans.length,
|
|
itemBuilder: (context, index) {
|
|
final plan = plans[index];
|
|
return UpcomingClassCard(
|
|
plan: plan,
|
|
onTap: () {
|
|
widget.onNavigateToPlanTab(1);
|
|
},
|
|
);
|
|
},
|
|
);
|
|
}
|
|
},
|
|
),
|
|
),
|
|
|
|
// --- ▼▼▼ 추천 클래스 섹션 호출 ▼▼▼ ---
|
|
// _buildRecommendSection(),
|
|
// --- ▲▲▲ 추천 클래스 섹션 호출 끝 ▲▲▲ ---
|
|
],
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final List<Widget> pageContents = _buildPageContents();
|
|
|
|
return Scaffold(
|
|
// appBar: AppBar( // AppBar 주석 처리됨 (기존 코드에서)
|
|
// title: Text(_selectedIndex == 0 ? 'Home' : 'Plan Page'),
|
|
// ),
|
|
body: IndexedStack( // AppBar가 없으므로 SafeArea로 감싸는 것을 고려해볼 수 있습니다.
|
|
index: 0,
|
|
children: pageContents,
|
|
)
|
|
);
|
|
}
|
|
} |