저장용

This commit is contained in:
girinb
2025-06-06 06:18:19 +09:00
commit b687722bd1
137 changed files with 7642 additions and 0 deletions

543
lib/home_page.dart Normal file
View File

@@ -0,0 +1,543 @@
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: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['planId'] ?? '아이디 없음',
planTitle: json['planTitle'] ?? '제목 없음',
planTeacher: json['planTeacher'] ?? '선생님 정보 없음',
thumbnail: json['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;
int _selectedIndex = 0;
// --- 추천 클래스 관련 상태 변수 ---
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.';
});
}
print('Could not get timezone: $e');
}
}
// --- 추천 클래스 데이터 가져오는 함수 ---
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) {
print('Error fetching recommend plans: $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(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
color: Theme.of(context).primaryColor.withOpacity(0.1),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Your Local Time', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0)),
const SizedBox(height: 6.0),
Text('$formattedDate, $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 _buildRecommendSection() {
if (_isLoadingRecommends) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 20.0),
child: Center(child: CircularProgressIndicator()),
);
}
if (_hasRecommendError) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 40),
const SizedBox(height: 8),
Text(
'Failed to load recommendations.\n$_recommendErrorText',
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.redAccent),
),
const SizedBox(height: 8),
ElevatedButton.icon(
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
onPressed: _fetchRecommendPlans,
)
],
),
),
);
}
if (_recommendPlans.isEmpty) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 20.0),
child: Center(child: Text('No recommendations available at the moment.')),
);
}
final currentPlan = _recommendPlans[_currentRecommendIndex];
return Container(
margin: const EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 16.0), // 하단 마진 추가
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
color: Theme.of(context).cardColor, // 카드 색상 사용
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'✨ Recommend Classes', // 이모지 추가
style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 12.0),
Text(
currentPlan.planName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w500),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
// Test: Plan ID 표시 (디버깅용)
// Text('ID: ${currentPlan.planId}', style: TextStyle(fontSize: 10, color: Colors.grey)),
AspectRatio(
aspectRatio: 16 / 9,
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: currentPlan.thumbnail.isNotEmpty
? Image.network(
currentPlan.thumbnail,
fit: BoxFit.cover,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Container( // 로딩 중 배경색 및 인디케이터 중앙 정렬 개선
color: Colors.grey[200],
child: Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
return Container(
color: Colors.grey[200],
child: const Center(child: Icon(Icons.broken_image, color: Colors.grey, size: 50)),
);
},
)
: Container(
color: Colors.grey[200],
child: const Center(child: Text('No Image Available', style: TextStyle(color: Colors.grey))),
),
),
)],
),
);
}
// --- 추천 클래스 섹션 위젯 끝 ---
Widget _buildHomeContent() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_buildLocalTimeBar(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: ElevatedButton.icon(
icon: const Icon(Icons.add_circle_outline, size: 20),
label: const Text('Book Class', style: TextStyle(fontSize: 14)),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Book Class 버튼 기능 구현 예정')),
);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
),
),
),
const SizedBox(width: 12.0),
Expanded(
child: 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),
),
),
),
),
],
),
),
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)),
),
Expanded(
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(
padding: const EdgeInsets.only(top: 8.0),
itemCount: plans.length,
itemBuilder: (context, index) {
final plan = plans[index];
return InkWell(
onTap: () {
// *** 부모 위젯(MyHomePage)에게 Plan 탭으로 이동하라고 알림 ***
// *** PlanPage가 _widgetOptions 리스트에서 두 번째(인덱스 1)라고 가정 ***
widget.onNavigateToPlanTab(1); // *** 전달받은 콜백 호출 ***
},
child: Card(
margin: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 16.0),
elevation: 2.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Text(
plan.planTitle,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
const SizedBox(width: 8.0),
Text(
plan.planTeacher,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey[600]),
),
],
),
const SizedBox(height: 8.0),
if (plan.thumbnail.isNotEmpty)
ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(
plan.thumbnail,
height: 150,
width: double.infinity,
fit: BoxFit.cover,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Container(
height: 150,
color: Colors.grey[200],
child: Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
return Container(height: 150, color: Colors.grey[200], child: const Center(child: Icon(Icons.broken_image, color: Colors.grey, size: 50)));
},
),
)
else
Container(height: 150, color: Colors.grey[200], child: const Center(child: Text('No Image', style: TextStyle(color: Colors.grey)))),
],
),
),
),
);
},
);
}
},
),
),
// --- ▼▼▼ 추천 클래스 섹션 호출 ▼▼▼ ---
_buildRecommendSection(),
// --- ▲▲▲ 추천 클래스 섹션 호출 끝 ▲▲▲ ---
],
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
// 홈 탭(인덱스 0)으로 돌아올 때 추천 타이머를 다시 시작할 수 있도록 고려
if (index == 0 && _recommendPlans.isNotEmpty && (_recommendTimer == null || !_recommendTimer!.isActive)) {
_startRecommendTimer();
} else if (index != 0) {
_recommendTimer?.cancel(); // 다른 탭으로 이동 시 타이머 일시 중지
}
});
}
@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: _selectedIndex,
children: pageContents,
)
);
}
}

161
lib/main.dart Normal file
View File

@@ -0,0 +1,161 @@
// main.dart
import 'package:flutter/material.dart';
// 새로 만든 페이지 파일들을 import 합니다.
import 'home_page.dart'; // HomePage에 콜백을 전달해야 하므로 import 경로 확인
import 'plan_page.dart';
import 'statistics_page.dart';
import 'more_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Case Study',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
// 각 탭에 연결될 페이지 위젯 리스트
// HomePage는 StatefulWidget이므로 const를 붙이지 않습니다.
// *** 수정: _widgetOptions를 late로 선언하고 initState에서 초기화 ***
late final List<Widget> _widgetOptions;
@override
void initState() {
super.initState();
// *** 수정: HomePage 생성 시 onNavigateToPlanTab 콜백 전달 ***
_widgetOptions = <Widget>[
HomePage(onNavigateToPlanTab: _onItemTapped), // 콜백 함수 전달
const PlanPage(),
const StatisticsPage(),
const MorePage(),
];
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
// HomePage의 _recommendTimer 제어 로직은 HomePage 내부에서 독립적으로 관리됩니다.
// 또는 필요에 따라 GlobalKey 등을 사용하여 HomePage의 상태에 접근할 수 있습니다.
}
// 프로필 탭(세 번째 탭, StatisticsPage)으로 이동하는 함수
void _navigateToProfileTab() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('프로필 눌림')),
);
// 필요하다면 여기서 _onItemTapped를 호출하여 특정 탭으로 이동할 수 있습니다.
// 예: _onItemTapped(2); // StatisticsPage로 이동
}
@override
Widget build(BuildContext context) {
// AppBar의 제목을 현재 탭에 따라 동적으로 변경
String appBarTitle = 'Home'; // 기본값
if (_selectedIndex == 1) {
appBarTitle = 'Plan';
} else if (_selectedIndex == 2) {
appBarTitle = 'Statistics';
} else if (_selectedIndex == 3) {
appBarTitle = 'More';
}
// --- BottomNavigationBar 크기 및 스타일 설정 ---
const double customBottomNavHeight = 75.0; // 원하는 BottomNavigationBar 높이
const double customBottomNavIconSize = 22.0; // 내부 아이콘 크기 (선택적 조절)
const double customBottomNavSelectedFontSize = 12.0; // 선택된 레이블 폰트 크기 (선택적 조절)
const double customBottomNavUnselectedFontSize = 10.0; // 미선택 레이블 폰트 크기 (선택적 조절)
return Scaffold(
appBar: AppBar(
toolbarHeight: 40,
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(appBarTitle), // 동적으로 변경된 AppBar 제목
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
tooltip: '알림',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('알림 아이콘 클릭됨')),
);
},
),
Padding(
padding: const EdgeInsets.only(right: 16.0),
child: InkWell(
onTap: _navigateToProfileTab,
customBorder: const CircleBorder(),
child: const CircleAvatar(
backgroundColor: Colors.grey,
child: Icon(
Icons.person,
color: Colors.white,
),
),
),
),
],
),
body: IndexedStack( // IndexedStack을 사용하여 페이지 상태 유지
index: _selectedIndex,
children: _widgetOptions,
),
bottomNavigationBar: SizedBox(
height: customBottomNavHeight,
child: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today_outlined),
label: 'Plan',
),
BottomNavigationBarItem(
icon: Icon(Icons.bar_chart_outlined),
label: 'Statistics',
),
BottomNavigationBarItem(
icon: Icon(Icons.more_horiz_outlined),
label: 'More',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
unselectedItemColor: Colors.blue,
onTap: _onItemTapped,
type: BottomNavigationBarType.fixed,
iconSize: customBottomNavIconSize,
selectedFontSize: customBottomNavSelectedFontSize,
unselectedFontSize: customBottomNavUnselectedFontSize,
),
),
);
}
}

17
lib/more_page.dart Normal file
View File

@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
class MorePage extends StatelessWidget {
const MorePage({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text(
'More Page',
style: TextStyle(fontSize: 24),
),
),
);
}
}

174
lib/plan_page.dart Normal file
View File

@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// HomePage에서 사용하던 CaseStudyPlan 모델을 PlanPage에서도 사용하거나,
// PlanPage에 필요한 별도의 데이터 모델을 정의할 수 있습니다.
// 여기서는 동일한 모델을 재사용한다고 가정합니다.
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['planId'] ?? 'ID 없음',
planTitle: json['planTitle'] ?? '제목 없음',
planTeacher: json['planTeacher'] ?? '선생님 정보 없음',
thumbnail: json['thumbnail'] ?? '',
);
}
}
class PlanPage extends StatefulWidget {
const PlanPage({super.key});
@override
State<PlanPage> createState() => _PlanPageState();
}
class _PlanPageState extends State<PlanPage> {
late Future<List<CaseStudyPlan>> _planPageData;
@override
void initState() {
super.initState();
// PlanPage가 처음 생성되거나 화면에 표시될 때 데이터를 가져옵니다.
_planPageData = _fetchPlanData();
}
Future<List<CaseStudyPlan>> _fetchPlanData() async {
// HomePage와 동일한 API 주소를 사용합니다.
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 for PlanPage: "data" field is missing or not a list.');
}
} else {
throw Exception(
'Failed to load data for PlanPage. Status Code: ${response.statusCode}');
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<CaseStudyPlan>>(
future: _planPageData,
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 PlanPage data: ${snapshot.error}', textAlign: TextAlign.center),
));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No data available for PlanPage.'));
} else {
// 데이터 로딩 성공 시 ListView 표시
final plans = snapshot.data!;
return ListView.builder(
itemCount: plans.length,
itemBuilder: (context, index) {
final plan = plans[index];
return Card(
margin:
const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
elevation: 2.0,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Text(
plan.planTitle,
style: const TextStyle(
fontSize: 17.0, fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8.0),
Text(
plan.planTeacher,
style: const TextStyle(
fontSize: 13.0, color: Colors.grey),
),
],
),
const SizedBox(height: 8.0),
if (plan.thumbnail.isNotEmpty)
ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(
plan.thumbnail,
height: 140, // 약간 작은 이미지 크기
width: double.infinity,
fit: BoxFit.cover,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes !=
null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
errorBuilder: (BuildContext context, Object exception,
StackTrace? stackTrace) {
return Container(
height: 140,
color: Colors.grey[200],
child: const Center(
child: Icon(Icons.broken_image,
color: Colors.grey, size: 40)));
},
),
)
else
Container(
height: 140,
color: Colors.grey[200],
child: const Center(
child: Text('No Image',
style: TextStyle(color: Colors.grey)))),
const SizedBox(height: 8.0),
// PlanPage용 ListView 아이템에 추가적인 정보를 표시하거나 다른 UI를 구성할 수 있습니다.
Text('Plan ID: ${plan.planId}', style: TextStyle(fontSize: 12.0, color: Colors.blueGrey)),
],
),
),
);
},
);
}
},
);
}
}

219
lib/plan_page_detail.dart Normal file
View File

@@ -0,0 +1,219 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'youtube_player_page.dart'; // YoutubePlayerPage import
// PlanDetailItem 클래스
class PlanDetailItem {
final String lessonId;
final String lessonTag;
final String lessonUrl;
final String thumbnail;
PlanDetailItem({
required this.lessonId,
required this.lessonTag,
required this.lessonUrl,
required this.thumbnail,
});
factory PlanDetailItem.fromJson(Map<String, dynamic> json) {
return PlanDetailItem(
lessonId: json['casestudy lesson id'] ?? 'ID 없음',
lessonTag: json['lesson tag'] ?? '태그 없음',
lessonUrl: json['lesson url'] ?? 'URL 없음',
thumbnail: json['thumbnail'] ?? '',
);
}
}
class plan_page_detail extends StatefulWidget {
// final int currentBottomNavIndex; // HomePage 등에서 전달받을 현재 탭 인덱스
const plan_page_detail({
super.key,
// this.currentBottomNavIndex = 0, // 기본값
});
@override
State<plan_page_detail> createState() => _plan_page_detailState();
}
class _plan_page_detailState extends State<plan_page_detail> {
String? _planId;
Future<List<PlanDetailItem>>? _planDetails;
late int _currentBottomNavIndex; // 하단 네비게이션 바 상태
@override
void initState() {
super.initState();
// 이전 페이지에서 전달받은 탭 인덱스로 초기화하거나 기본값 사용
// _currentBottomNavIndex = widget.currentBottomNavIndex;
_currentBottomNavIndex = 0; // 예시: '홈' 탭을 기본으로 설정
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_planId == null) {
final Object? arguments = ModalRoute.of(context)?.settings.arguments;
if (arguments is String) {
_planId = arguments;
if (_planId != null) {
_planDetails = _fetchPlanDetails(_planId!);
}
} else {
_planDetails = Future.error(Exception("Plan ID not provided or invalid."));
print("Error: Plan ID not provided or invalid.");
}
}
}
Future<List<PlanDetailItem>> _fetchPlanDetails(String planId) async {
final response = await http
.get(Uri.parse('https://helloworld1-ad2uqhckxq-uc.a.run.app/?id=$planId'));
if (response.statusCode == 200) {
final Map<String, dynamic> decodedJson = json.decode(response.body);
if (decodedJson.containsKey('data') && decodedJson['data'] is List) {
final List<dynamic> detailsJson = decodedJson['data'];
return detailsJson.map((jsonItem) => PlanDetailItem.fromJson(jsonItem as Map<String, dynamic>)).toList();
} else {
throw Exception('Invalid API response format: "data" field is missing or not a list.');
}
} else {
throw Exception('Failed to load plan details. Status code: ${response.statusCode}');
}
}
void _onBottomNavItemTapped(int index) {
setState(() {
_currentBottomNavIndex = index;
});
// 페이지 이동 로직 (이전 답변 참고)
if (index == 0) {
Navigator.of(context).popUntil((route) => route.isFirst);
} else if (index == 1) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Search (Not Implemented)')),
);
} else if (index == 2) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Profile (Not Implemented)')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
// 1. 상단 바 (AppBar)
appBar: AppBar(
title: Text(_planId != null ? 'Plan: $_planId' : 'Plan Details'),
// 필요하다면 leading에 뒤로가기 버튼 명시적 추가
leading: Navigator.canPop(context)
? IconButton(
icon: const Icon(Icons.arrow_back_ios_new), // 또는 Icons.arrow_back
tooltip: 'Back',
onPressed: () => Navigator.of(context).pop(),
)
: null,
),
body: _planId == null
? const Center(
child: Text(
'Plan ID가 전달되지 않았습니다.',
style: TextStyle(fontSize: 18, color: Colors.red),
),
)
: FutureBuilder<List<PlanDetailItem>>(
future: _planDetails,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('세부 계획 데이터가 없습니다.'));
} else {
final details = snapshot.data!;
return ListView.builder(
itemCount: details.length,
itemBuilder: (context, index) {
final item = details[index];
return Card(
margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListTile(
leading: item.thumbnail.isNotEmpty
? SizedBox(
width: 100,
height: 100,
child: Image.network(
item.thumbnail,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.broken_image, size: 40, color: Colors.grey);
},
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
: null,
),
);
},
),
)
: Container(
width: 100,
height: 100,
color: Colors.grey[200],
child: const Icon(Icons.image_not_supported, size: 40, color: Colors.grey),
),
title: Text(item.lessonTag, style: const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text('ID: ${item.lessonId}', style: TextStyle(fontSize: 12, color: Colors.grey[700])),
const SizedBox(height: 2),
Text(
item.lessonUrl,
style: const TextStyle(fontSize: 12, color: Colors.blueAccent),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
],
),
isThreeLine: true,
onTap: () {
if (item.lessonUrl.isNotEmpty && (item.lessonUrl.contains('youtube.com') || item.lessonUrl.contains('youtu.be'))) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => YoutubePlayerPage(
lessonUrl: item.lessonUrl,
// currentBottomNavIndex: _currentBottomNavIndex, // 현재 탭 인덱스 전달
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('유효한 YouTube URL이 아닙니다: ${item.lessonUrl}')),
);
}
},
),
);
},
);
}
},
),
// 2. 하단 바 (BottomNavigationBar)
);
}
}

17
lib/statistics_page.dart Normal file
View File

@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
class StatisticsPage extends StatelessWidget {
const StatisticsPage({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text(
'Statistics Page',
style: TextStyle(fontSize: 24),
),
),
);
}
}

View File

@@ -0,0 +1,316 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // SystemChrome, DeviceOrientation 사용을 위해 import
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class YoutubePlayerPage extends StatefulWidget {
final String lessonUrl;
// final int currentBottomNavIndex;
const YoutubePlayerPage({
super.key,
required this.lessonUrl,
// this.currentBottomNavIndex = 0,
});
@override
State<YoutubePlayerPage> createState() => _YoutubePlayerPageState();
}
class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
YoutubePlayerController? _controller;
String? _videoId;
bool _isPlayerReady = false;
String _videoTitle = 'YouTube Video';
final int _currentBottomNavIndex = 0;
bool _isSystemUiVisible = true;
@override
void initState() {
super.initState();
// 페이지 진입 시 기본 화면 방향 설정 (선택적)
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ]);
_videoId = YoutubePlayer.convertUrlToId(widget.lessonUrl);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
final String snackBarMessage;
if (_videoId != null) {
snackBarMessage = 'Video ID: $_videoId';
} else {
snackBarMessage =
'Could not extract Video ID from URL: ${widget.lessonUrl}';
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(snackBarMessage),
duration: const Duration(seconds: 3),
),
);
}
});
if (_videoId != null) {
_controller = YoutubePlayerController(
initialVideoId: _videoId!,
flags: const YoutubePlayerFlags(
autoPlay: true,
mute: false,
),
)..addListener(_playerListener);
} else {
print("Error: Could not extract video ID from URL: ${widget.lessonUrl}");
_videoTitle = 'Video Error';
}
}
void _playerListener() {
if (_controller == null || !mounted) return;
if (_controller!.value.isFullScreen) {
_hideSystemUi();
// 플레이어가 전체 화면으로 진입하면 가로 방향으로 설정 (선택적, 플레이어가 자동으로 할 수 있음)
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.landscapeLeft,
// DeviceOrientation.landscapeRight,
// ]);
} else {
_showSystemUi();
// <<< 전체 화면이 해제되면 화면 방향을 세로로 복구 >>>
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
if (_isPlayerReady) {
if (_controller!.metadata.title.isNotEmpty &&
_videoTitle != _controller!.metadata.title) {
if (mounted) {
setState(() {
_videoTitle = _controller!.metadata.title;
});
}
}
}
}
void _hideSystemUi() {
if (!_isSystemUiVisible) return;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
if (mounted) {
setState(() {
_isSystemUiVisible = false;
});
}
}
void _showSystemUi() {
if (_isSystemUiVisible) return;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
if (mounted) {
setState(() {
_isSystemUiVisible = true;
});
}
}
void _onNotificationTapped() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('알림 아이콘 클릭됨')),
);
}
void _onProfileTapped() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('프로필 아이콘 클릭됨')),
);
}
void _onBottomNavItemTapped(int index) {
if (_currentBottomNavIndex == index && index != 0) return;
if (index == 0) {
Navigator.of(context).popUntil((route) => route.isFirst);
} else {
String tabName = '';
switch (index) {
case 1:
tabName = 'Plan';
break;
case 2:
tabName = 'Statistics';
break;
case 3:
tabName = 'More';
break;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('$tabName 탭으로 이동 (구현 필요)')),
);
}
}
// <<< 뒤로가기 버튼 처리 로직 >>>
Future<bool> _onWillPop() async {
if (_controller != null && _controller!.value.isFullScreen) {
_controller!.toggleFullScreenMode(); // 전체 화면 해제
// _playerListener에서 화면 방향은 자동으로 세로로 설정될 것임
// _showSystemUi(); // 시스템 UI도 _playerListener에서 처리
return false; // 뒤로가기(페이지 pop) 막음
}
// 전체 화면이 아닐 때는 일반적인 뒤로 가기 동작 허용
return true;
}
@override
Widget build(BuildContext context) {
final bool isFullScreen = _controller?.value.isFullScreen ?? false;
// <<< WillPopScope로 Scaffold를 감싸서 뒤로가기 이벤트 가로채기 >>>
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
extendBodyBehindAppBar: isFullScreen,
appBar: isFullScreen
? null
: AppBar(
leading: Navigator.canPop(context)
? IconButton(
icon: const Icon(Icons.arrow_back_ios_new),
// <<< AppBar의 뒤로가기 버튼도 _onWillPop 로직을 따르도록 수정 >>>
onPressed: () async {
if (await _onWillPop()) {
// true를 반환하면 (즉, 전체화면이 아니면) 페이지 pop
Navigator.pop(context);
}
},
)
: null,
title: Text(_videoTitle),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications_none),
tooltip: '알림',
onPressed: _onNotificationTapped,
),
Padding(
padding: const EdgeInsets.only(right: 16.0, left: 8.0),
child: InkWell(
onTap: _onProfileTapped,
customBorder: const CircleBorder(),
child: const CircleAvatar(
radius: 16,
backgroundColor: Colors.grey,
child: Icon(
Icons.person,
size: 20,
color: Colors.white,
),
),
),
),
],
),
body: Center(
child: _controller == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline,
color: Colors.red, size: 50),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Text(
'비디오를 로드할 수 없습니다.\nURL: ${widget.lessonUrl}',
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 16),
),
),
],
)
: YoutubePlayer(
controller: _controller!,
showVideoProgressIndicator: true,
progressIndicatorColor: Colors.amber,
progressColors: const ProgressBarColors(
playedColor: Colors.amber,
handleColor: Colors.amberAccent,
),
onReady: () {
if (mounted) {
setState(() {
_isPlayerReady = true;
if (_controller!.metadata.title.isNotEmpty) {
_videoTitle = _controller!.metadata.title;
}
});
}
print('Player is ready.');
},
),
),
bottomNavigationBar: isFullScreen
? null
: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today_outlined),
label: 'Plan',
),
BottomNavigationBarItem(
icon: Icon(Icons.bar_chart_outlined),
label: 'Statistics',
),
BottomNavigationBarItem(
icon: Icon(Icons.more_horiz_outlined),
label: 'More',
),
],
currentIndex: _currentBottomNavIndex,
selectedItemColor: Colors.amber[800],
unselectedItemColor: Colors.blue,
onTap: _onBottomNavItemTapped,
type: BottomNavigationBarType.fixed,
),
),
);
}
@override
void deactivate() {
if (_controller != null && _isPlayerReady) {
_controller!.pause();
}
super.deactivate();
}
@override
void dispose() {
// <<< 페이지 종료 시 기본 화면 방향으로 복구 또는 모든 방향 허용 >>>
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
// DeviceOrientation.landscapeLeft, // 필요에 따라 가로모드도 허용
// DeviceOrientation.landscapeRight,
]);
// 또는: SystemChrome.setPreferredOrientations(DeviceOrientation.values); // 모든 방향 허용
// 시스템 UI 복구 (이미 _showSystemUi()가 있지만, 명시적으로 호출)
// _showSystemUi(); // 이 로직은 _isSystemUiVisible 상태에 따라 실행되므로 안전
// 또는 강제로 UI를 보이게 하려면:
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
_controller?.removeListener(_playerListener);
_controller?.dispose();
super.dispose();
}
}