Compare commits

...

3 Commits

Author SHA1 Message Date
girinb
42453abe41 2025-07-11
작업 시작전 저장
2025-07-11 13:49:46 +09:00
girinb
2ad2af76e0 리스트뷰 가로로 수정 2025-07-10 18:45:20 +09:00
girinb
ae99bd661d 한번 좆되서 다시 돌림 2025-07-10 18:31:19 +09:00
7 changed files with 537 additions and 358 deletions

62
lib/career_page.dart Normal file
View File

@@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import 'package:csp2/common/widgets/custom_bottom_nav_bar.dart';
class JobsPage extends StatefulWidget {
const JobsPage({super.key});
@override
State<JobsPage> createState() => _JobsPageState();
}
class _JobsPageState extends State<JobsPage> {
int _selectedIndex = 3; // Assuming Jobs is the 4th item (index 3)
String? _selectedDropdownValue; // 드롭다운 선택 값 저장 변수
@override
void initState() {
super.initState();
_selectedDropdownValue = 'Indonesia'; // 초기값 설정
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
// TODO: Add navigation logic here based on index
// For now, we'll just print the index
print('Tapped index: $index');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16.0), // 상단에 패딩 추가
child: Column(
mainAxisAlignment: MainAxisAlignment.start, // 상단 정렬
crossAxisAlignment: CrossAxisAlignment.start, // 왼쪽 정렬
children: [
DropdownButton<String>(
value: _selectedDropdownValue,
onChanged: (String? newValue) {
setState(() {
_selectedDropdownValue = newValue;
});
},
items: <String>['Indonesia', 'Hongkong', 'Singapore', 'South Korea',' Japan']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
const SizedBox(height: 20),
Text('Selected: $_selectedDropdownValue'),
],
),
),
);
}
}

View File

@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
class CustomBottomNavBar extends StatelessWidget {
final int currentIndex;
final Function(int) onTap;
const CustomBottomNavBar({
super.key,
required this.currentIndex,
required this.onTap,
});
@override
Widget build(BuildContext context) {
const double customBottomNavHeight = 94.0;
const double customBottomNavIconSize = 22.0;
const double customBottomNavSelectedFontSize = 10.0;
const double customBottomNavUnselectedFontSize = 8.0;
return 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.work_outline),
label: 'Career',
),
BottomNavigationBarItem(
icon: Icon(Icons.more_horiz_outlined),
label: 'More',
),
],
currentIndex: currentIndex,
unselectedItemColor: Colors.blue,
onTap: onTap,
type: BottomNavigationBarType.fixed,
iconSize: customBottomNavIconSize,
selectedFontSize: customBottomNavSelectedFontSize,
unselectedFontSize: customBottomNavUnselectedFontSize,
),
);
}
}

View File

@@ -22,10 +22,10 @@ class CaseStudyPlan {
factory CaseStudyPlan.fromJson(Map<String, dynamic> json) { factory CaseStudyPlan.fromJson(Map<String, dynamic> json) {
return CaseStudyPlan( return CaseStudyPlan(
planId: json['planId'] ?? '아이디 없음', planId: json['casestudy lesson id'] ?? '아이디 없음',
planTitle: json['planTitle'] ?? '제목 없음', planTitle: json['course_name'] ?? '제목 없음',
planTeacher: json['planTeacher'] ?? '선생님 정보 없음', planTeacher: json['planTeacher'] ?? '',
thumbnail: json['thumbnail'] ?? '', thumbnail: json['course_thumbnail'] ?? '',
); );
} }
} }
@@ -460,7 +460,8 @@ class _HomePageState extends State<HomePage> {
), ),
const SizedBox(width: 8.0), const SizedBox(width: 8.0),
Text( Text(
plan.planTeacher, // plan.planTeacher,
"",
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey[600]), style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey[600]),
), ),
], ],
@@ -508,7 +509,7 @@ class _HomePageState extends State<HomePage> {
), ),
// --- ▼▼▼ 추천 클래스 섹션 호출 ▼▼▼ --- // --- ▼▼▼ 추천 클래스 섹션 호출 ▼▼▼ ---
_buildRecommendSection(), // _buildRecommendSection(),
// --- ▲▲▲ 추천 클래스 섹션 호출 끝 ▲▲▲ --- // --- ▲▲▲ 추천 클래스 섹션 호출 끝 ▲▲▲ ---
], ],
); );

View File

@@ -6,7 +6,9 @@ import 'package:flutter/material.dart';
import 'home_page.dart'; // HomePage에 콜백을 전달해야 하므로 import 경로 확인 import 'home_page.dart'; // HomePage에 콜백을 전달해야 하므로 import 경로 확인
import 'plan_page.dart'; import 'plan_page.dart';
import 'statistics_page.dart'; import 'statistics_page.dart';
import 'career_page.dart';
import 'more_page.dart'; import 'more_page.dart';
import 'common/widgets/custom_bottom_nav_bar.dart';
void main() { void main() {
runApp(const MyApp()); runApp(const MyApp());
@@ -29,14 +31,15 @@ class MyApp extends StatelessWidget {
} }
class MyHomePage extends StatefulWidget { class MyHomePage extends StatefulWidget {
const MyHomePage({super.key}); final int initialIndex;
const MyHomePage({super.key, this.initialIndex = 0});
@override @override
State<MyHomePage> createState() => _MyHomePageState(); State<MyHomePage> createState() => _MyHomePageState();
} }
class _MyHomePageState extends State<MyHomePage> { class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0; late int _selectedIndex;
// 각 탭에 연결될 페이지 위젯 리스트 // 각 탭에 연결될 페이지 위젯 리스트
// HomePage는 StatefulWidget이므로 const를 붙이지 않습니다. // HomePage는 StatefulWidget이므로 const를 붙이지 않습니다.
@@ -46,11 +49,13 @@ class _MyHomePageState extends State<MyHomePage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_selectedIndex = widget.initialIndex;
// *** 수정: HomePage 생성 시 onNavigateToPlanTab 콜백 전달 *** // *** 수정: HomePage 생성 시 onNavigateToPlanTab 콜백 전달 ***
_widgetOptions = <Widget>[ _widgetOptions = <Widget>[
HomePage(onNavigateToPlanTab: _onItemTapped), // 콜백 함수 전달 HomePage(onNavigateToPlanTab: _onItemTapped), // 콜백 함수 전달
const PlanPage(), const PlanPage(),
const StatisticsPage(), const StatisticsPage(),
const JobsPage(),
const MorePage(), const MorePage(),
]; ];
} }
@@ -59,6 +64,7 @@ class _MyHomePageState extends State<MyHomePage> {
setState(() { setState(() {
_selectedIndex = index; _selectedIndex = index;
}); });
print('Selected index: $_selectedIndex'); // 디버깅 출력 추가
// HomePage의 _recommendTimer 제어 로직은 HomePage 내부에서 독립적으로 관리됩니다. // HomePage의 _recommendTimer 제어 로직은 HomePage 내부에서 독립적으로 관리됩니다.
// 또는 필요에 따라 GlobalKey 등을 사용하여 HomePage의 상태에 접근할 수 있습니다. // 또는 필요에 따라 GlobalKey 등을 사용하여 HomePage의 상태에 접근할 수 있습니다.
} }
@@ -78,23 +84,22 @@ class _MyHomePageState extends State<MyHomePage> {
String appBarTitle = 'Home'; // 기본값 String appBarTitle = 'Home'; // 기본값
if (_selectedIndex == 1) { if (_selectedIndex == 1) {
appBarTitle = 'Plan'; appBarTitle = 'Plan';
} else if (_selectedIndex == 2) { }
else if (_selectedIndex == 2) {
appBarTitle = 'Statistics'; appBarTitle = 'Statistics';
} else if (_selectedIndex == 3) { }
else if (_selectedIndex == 3) {
appBarTitle = 'Career';
}
else if (_selectedIndex == 4) {
appBarTitle = 'More'; 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( return Scaffold(
appBar: AppBar( appBar: AppBar(
toolbarHeight: 40, toolbarHeight: 40,
backgroundColor: Theme.of(context).colorScheme.inversePrimary, backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(appBarTitle), // 동적으로 변경된 AppBar 제목 title: Text(appBarTitle), // 동적으로 변경된 AppBar 제목\
actions: <Widget>[ actions: <Widget>[
IconButton( IconButton(
icon: const Icon(Icons.notifications), icon: const Icon(Icons.notifications),
@@ -125,36 +130,9 @@ class _MyHomePageState extends State<MyHomePage> {
index: _selectedIndex, index: _selectedIndex,
children: _widgetOptions, children: _widgetOptions,
), ),
bottomNavigationBar: SizedBox( bottomNavigationBar: CustomBottomNavBar(
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, currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
unselectedItemColor: Colors.blue,
onTap: _onItemTapped, onTap: _onItemTapped,
type: BottomNavigationBarType.fixed,
iconSize: customBottomNavIconSize,
selectedFontSize: customBottomNavSelectedFontSize,
unselectedFontSize: customBottomNavUnselectedFontSize,
),
), ),
); );
} }

View File

@@ -21,10 +21,10 @@ class CaseStudyPlan {
factory CaseStudyPlan.fromJson(Map<String, dynamic> json) { factory CaseStudyPlan.fromJson(Map<String, dynamic> json) {
return CaseStudyPlan( return CaseStudyPlan(
planId: json['planId'] ?? 'ID 없음', planId: json['casestudy lesson id'] ?? '아이디 없음',
planTitle: json['planTitle'] ?? '제목 없음', planTitle: json['course_name'] ?? '제목 없음',
planTeacher: json['planTeacher'] ?? '선생님 정보 없음', planTeacher: json['planTeacher'] ?? '',
thumbnail: json['thumbnail'] ?? '', thumbnail: json['course_thumbnail'] ?? '',
); );
} }
} }
@@ -80,8 +80,10 @@ class _PlanPageState extends State<PlanPage> {
return Center( return Center(
child: Padding( child: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: Text('Error loading PlanPage data: ${snapshot.error}', textAlign: TextAlign.center), child: Text('Error loading PlanPage data: ${snapshot.error}', textAlign: TextAlign.center,
)); maxLines: 3,
overflow: TextOverflow.ellipsis,
)));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) { } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No data available for PlanPage.')); return const Center(child: Text('No data available for PlanPage.'));
} else { } else {
@@ -91,9 +93,8 @@ class _PlanPageState extends State<PlanPage> {
itemCount: plans.length, itemCount: plans.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final plan = plans[index]; final plan = plans[index];
return InkWell( // <<< Card를 InkWell로 감싸서 탭 이벤트를 추가합니다. return InkWell(
onTap: () { onTap: () {
// plan_page_detail로 이동하면서 planId를 arguments로 전달
if (plan.planId == 'ID 없음' || plan.planId.isEmpty) { if (plan.planId == 'ID 없음' || plan.planId.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('유효한 Plan ID가 없어 상세 페이지로 이동할 수 없습니다.')), const SnackBar(content: Text('유효한 Plan ID가 없어 상세 페이지로 이동할 수 없습니다.')),
@@ -103,20 +104,18 @@ class _PlanPageState extends State<PlanPage> {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => const plan_page_detail(), // plan_page_detail 위젯을 생성 builder: (context) => const PlanPageDetail(),
settings: RouteSettings( settings: RouteSettings(
arguments: plan.planId, // 선택된 plan의 ID를 전달 // <<< Map 형태로 planId와 planTitle을 전달 >>>
arguments: {
'planId': plan.planId,
'planTitle': plan.planTitle,
},
), ),
), ),
); );
// 만약 Named Route를 사용하고 main.dart에 '/plan_detail' 라우트가 정의되어 있다면:
// Navigator.pushNamed(
// context,
// '/plan_detail', // MaterialApp에 정의된 라우트 이름
// arguments: plan.planId,
// );
}, },
child: Card( // <<< 기존 Card 위젯 child: Card(
margin: margin:
const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
elevation: 2.0, elevation: 2.0,
@@ -134,6 +133,7 @@ class _PlanPageState extends State<PlanPage> {
style: const TextStyle( style: const TextStyle(
fontSize: 17.0, fontWeight: FontWeight.bold), fontSize: 17.0, fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
maxLines: 2,
), ),
), ),
const SizedBox(width: 8.0), const SizedBox(width: 8.0),
@@ -141,18 +141,22 @@ class _PlanPageState extends State<PlanPage> {
plan.planTeacher, plan.planTeacher,
style: const TextStyle( style: const TextStyle(
fontSize: 13.0, color: Colors.grey), fontSize: 13.0, color: Colors.grey),
maxLines: 1,
overflow: TextOverflow.ellipsis,
), ),
], ],
), ),
const SizedBox(height: 8.0), const SizedBox(height: 8.0),
if (plan.thumbnail.isNotEmpty) if (plan.thumbnail.isNotEmpty)
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(8.0), borderRadius: BorderRadius.circular(8.0),
child: Image.network( child: Image.network(
plan.thumbnail, plan.thumbnail,
height: 140, // 약간 작은 이미지 크기 height: 120,
width: double.infinity, width: double.infinity,
fit: BoxFit.cover, fit: BoxFit.contain,
alignment: Alignment.centerLeft,
loadingBuilder: (BuildContext context, Widget child, loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) { ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child; if (loadingProgress == null) return child;
@@ -184,9 +188,6 @@ class _PlanPageState extends State<PlanPage> {
child: const Center( child: const Center(
child: Text('No Image', child: Text('No Image',
style: TextStyle(color: Colors.grey)))), 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)),
], ],
), ),
), ),

View File

@@ -1,20 +1,26 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'dart:convert'; import 'dart:convert';
import 'main.dart';
import 'youtube_player_page.dart'; // YoutubePlayerPage import import 'youtube_player_page.dart'; // YoutubePlayerPage import
import 'common/widgets/custom_bottom_nav_bar.dart';
// PlanDetailItem 클래스 // PlanDetailItem 클래스 (이전과 동일)
class PlanDetailItem { class PlanDetailItem {
final String lessonId; final String lessonId;
final String lessonTag; final String lessonTag;
final String lessonUrl; final String lessonUrl;
final String thumbnail; final String thumbnail;
final String lessonName;
final String lessonDescription;
PlanDetailItem({ PlanDetailItem({
required this.lessonId, required this.lessonId,
required this.lessonTag, required this.lessonTag,
required this.lessonUrl, required this.lessonUrl,
required this.thumbnail, required this.thumbnail,
required this.lessonName,
required this.lessonDescription,
}); });
factory PlanDetailItem.fromJson(Map<String, dynamic> json) { factory PlanDetailItem.fromJson(Map<String, dynamic> json) {
@@ -23,66 +29,88 @@ class PlanDetailItem {
lessonTag: json['lesson tag'] ?? '태그 없음', lessonTag: json['lesson tag'] ?? '태그 없음',
lessonUrl: json['lesson url'] ?? 'URL 없음', lessonUrl: json['lesson url'] ?? 'URL 없음',
thumbnail: json['thumbnail'] ?? '', thumbnail: json['thumbnail'] ?? '',
lessonName: json['lesson_name'] ?? '이름 없음',
lessonDescription: json['lesson_description'] ?? '설명 없음',
); );
} }
} }
class plan_page_detail extends StatefulWidget { class PlanPageDetail extends StatefulWidget {
// final int currentBottomNavIndex; // HomePage 등에서 전달받을 현재 탭 인덱스 const PlanPageDetail({
const plan_page_detail({
super.key, super.key,
// this.currentBottomNavIndex = 0, // 기본값
}); });
@override @override
State<plan_page_detail> createState() => _plan_page_detailState(); State<PlanPageDetail> createState() => _PlanPageDetailState();
} }
class _plan_page_detailState extends State<plan_page_detail> { class _PlanPageDetailState extends State<PlanPageDetail> {
String? _planId; String? _planId;
String? _planTitle; // <<< planTitle을 저장할 상태 변수 추가 >>>
Future<List<PlanDetailItem>>? _planDetails; Future<List<PlanDetailItem>>? _planDetails;
late int _currentBottomNavIndex; // 하단 네비게이션 바 상태 late int _currentBottomNavIndex;
String? _selectedYoutubeUrl;
PlanDetailItem? _selectedItem; // <<< 선택된 아이템을 저장할 변수 추가
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// 이전 페이지에서 전달받은 탭 인덱스로 초기화하거나 기본값 사용 _currentBottomNavIndex = 0;
// _currentBottomNavIndex = widget.currentBottomNavIndex;
_currentBottomNavIndex = 0; // 예시: '홈' 탭을 기본으로 설정
} }
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();
if (_planId == null) { // 인자를 한 번만 처리하도록 조건 추가
if (_planId == null && _planTitle == null) {
final Object? arguments = ModalRoute.of(context)?.settings.arguments; final Object? arguments = ModalRoute.of(context)?.settings.arguments;
if (arguments is String) { if (arguments is Map<String, String>) { // <<< 전달받은 인자가 Map인지 확인 >>>
_planId = arguments; setState(() { // <<< setState로 상태 변수 업데이트 >>>
_planId = arguments['planId'];
_planTitle = arguments['planTitle'];
});
if (_planId != null) { if (_planId != null) {
_planDetails = _fetchPlanDetails(_planId!); _planDetails = _fetchPlanDetails(_planId!);
} else {
// Map에는 있지만 planId 키가 없는 경우 (이론상 발생하기 어려움)
setState(() {
_planTitle = arguments['planTitle'] ?? 'Error'; // planTitle은 있을 수 있음
});
_planDetails =
Future.error(Exception("Plan ID가 Map에 포함되지 않았습니다."));
} }
} else { } else {
_planDetails = Future.error(Exception("Plan ID not provided or invalid.")); // 인자가 Map이 아니거나 null인 경우
print("Error: Plan ID not provided or invalid."); setState(() {
_planTitle = 'Error'; // AppBar에 오류 표시
});
_planDetails =
Future.error(Exception("전달된 인자가 올바르지 않습니다. (Map<String, String> 형태여야 함)"));
} }
} }
} }
Future<List<PlanDetailItem>> _fetchPlanDetails(String planId) async { Future<List<PlanDetailItem>> _fetchPlanDetails(String planId) async {
final response = await http final response = await http.get(
.get(Uri.parse('https://helloworld1-ad2uqhckxq-uc.a.run.app/?id=$planId')); Uri.parse('https://helloworld1-ad2uqhckxq-uc.a.run.app/?id=$planId'));
if (response.statusCode == 200) { if (response.statusCode == 200) {
final Map<String, dynamic> decodedJson = json.decode(response.body); final Map<String, dynamic> decodedJson = json.decode(response.body);
if (decodedJson.containsKey('data') && decodedJson['data'] is List) { if (decodedJson.containsKey('data') && decodedJson['data'] is List) {
final List<dynamic> detailsJson = decodedJson['data']; final List<dynamic> detailsJson = decodedJson['data'];
return detailsJson.map((jsonItem) => PlanDetailItem.fromJson(jsonItem as Map<String, dynamic>)).toList(); return detailsJson
.map((jsonItem) =>
PlanDetailItem.fromJson(jsonItem as Map<String, dynamic>))
.toList();
} else { } else {
throw Exception('Invalid API response format: "data" field is missing or not a list.'); throw Exception(
'Invalid API response format: "data" field is missing or not a list.');
} }
} else { } else {
throw Exception('Failed to load plan details. Status code: ${response.statusCode}'); throw Exception(
'Failed to load plan details. Status code: ${response.statusCode}');
} }
} }
@@ -90,41 +118,30 @@ class _plan_page_detailState extends State<plan_page_detail> {
setState(() { setState(() {
_currentBottomNavIndex = index; _currentBottomNavIndex = index;
}); });
// 페이지 이동 로직 (이전 답변 참고) Navigator.of(context).pushAndRemoveUntil(
if (index == 0) { MaterialPageRoute(builder: (context) => MyHomePage(initialIndex: index)),
Navigator.of(context).popUntil((route) => route.isFirst); (Route<dynamic> route) => false,
} 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
// 1. 상단 바 (AppBar)
appBar: AppBar( appBar: AppBar(
title: Text(_planId != null ? 'Plan: $_planId' : 'Plan Details'), toolbarHeight: 40,
// 필요하다면 leading에 뒤로가기 버튼 명시적 추가 title: Text(_planTitle.toString()),
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 body: _planId == null && _planTitle == null && _planDetails == null
? const Center( ? Center( // 초기 로딩 상태 또는 인자 오류
child: Text( child: _planTitle == 'Error'
'Plan ID가 전달되지 않았습니다.', ? const Text(
'플랜 정보를 불러올 수 없습니다.',
style: TextStyle(fontSize: 18, color: Colors.red), style: TextStyle(fontSize: 18, color: Colors.red),
), textAlign: TextAlign.center,
maxLines: 3,
overflow: TextOverflow.ellipsis,
)
: const CircularProgressIndicator(),
) )
: FutureBuilder<List<PlanDetailItem>>( : FutureBuilder<List<PlanDetailItem>>(
future: _planDetails, future: _planDetails,
@@ -132,88 +149,223 @@ class _plan_page_detailState extends State<plan_page_detail> {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) { } else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}')); return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text('Error loading details: ${snapshot.error}', textAlign: TextAlign.center,
maxLines: 3,
overflow: TextOverflow.ellipsis,
)));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) { } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('세부 계획 데이터가 없습니다.')); return const Center(child: Text('세부 계획 데이터가 없습니다.'));
} else { } else {
final details = snapshot.data!; final details = snapshot.data!;
return ListView.builder( if (_selectedItem == null && details.isNotEmpty) {
_selectedItem = details.first;
}
// 첫 번째 비디오의 URL을 가져와 _selectedYoutubeUrl을 초기화합니다.
if (_selectedYoutubeUrl == null && details.isNotEmpty) {
_selectedYoutubeUrl = details.firstWhere(
(item) => item.lessonUrl.isNotEmpty &&
(item.lessonUrl.contains('youtube.com') ||
item.lessonUrl.contains('youtu.be')),
orElse: () => PlanDetailItem(lessonId: '', lessonTag: '', lessonUrl: '', thumbnail: '',lessonName: '', lessonDescription: ''),
).lessonUrl.isNotEmpty ? details.firstWhere(
(item) => item.lessonUrl.isNotEmpty &&
(item.lessonUrl.contains('youtube.com') ||
item.lessonUrl.contains('youtu.be')),
orElse: () => PlanDetailItem(lessonId: '', lessonTag: '', lessonUrl: '', thumbnail: '',lessonName: '', lessonDescription: ''),
).lessonUrl : null;
}
return Column( // ListView와 YoutubePlayerPage를 세로로 배치하기 위해 Column 사용
children: [
SizedBox(
height: 150, // 가로 스크롤 리스트의 높이
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8.0),
itemCount: details.length, itemCount: details.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = details[index]; final item = details[index];
return Card( return GestureDetector(
margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), onTap: () {
child: ListTile( setState(() {
leading: item.thumbnail.isNotEmpty _selectedItem = item;
? SizedBox( if (item.lessonUrl.isNotEmpty &&
(item.lessonUrl.contains('youtube.com') ||
item.lessonUrl.contains('youtu.be'))) {
_selectedYoutubeUrl = item.lessonUrl;
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'유효한 YouTube URL이 아닙니다: ${item.lessonUrl}')),
);
}
});
},
child: Container(
width: 110,
margin: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 100, width: 100,
height: 100, height: 100,
child: Image.network( child: ClipRRect(
borderRadius:
BorderRadius.circular(8.0),
child: item.thumbnail.isNotEmpty
? Image.network(
item.thumbnail, item.thumbnail,
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) { errorBuilder: (context, error,
return const Icon(Icons.broken_image, size: 40, color: Colors.grey); stackTrace) {
return Container(
color: Colors.grey[200],
child: const Icon(
Icons.broken_image,
size: 40,
color: Colors.grey),
);
}, },
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) { loadingBuilder: (BuildContext
if (loadingProgress == null) return child; context,
Widget child,
ImageChunkEvent?
loadingProgress) {
if (loadingProgress == null)
return child;
return Center( return Center(
child: CircularProgressIndicator( child:
value: loadingProgress.expectedTotalBytes != null CircularProgressIndicator(
? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes! value: loadingProgress
.expectedTotalBytes !=
null
? loadingProgress
.cumulativeBytesLoaded /
loadingProgress
.expectedTotalBytes!
: null, : null,
strokeWidth: 2.0,
), ),
); );
}, },
)
: Container(
color: Colors.grey[200],
child: const Icon(
Icons.image_not_supported,
size: 40,
color: Colors.grey),
),
),
),
const SizedBox(height: 6),
Text(
item.lessonTag,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
],
),
),
);
},
),
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_selectedItem!.thumbnail.isNotEmpty
? ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.network(
_selectedItem!.thumbnail,
height: 200,
width: double.infinity,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
height: 200,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(12.0),
),
child: const Icon(Icons.broken_image, size: 60, color: Colors.grey),
);
},
), ),
) )
: Container( : Container(
width: 100, height: 200,
height: 100, width: double.infinity,
color: Colors.grey[200], decoration: BoxDecoration(
child: const Icon(Icons.image_not_supported, size: 40, color: Colors.grey), color: Colors.grey[300],
borderRadius: BorderRadius.circular(12.0),
), ),
title: Text(item.lessonTag, style: const TextStyle(fontWeight: FontWeight.bold)), child: const Icon(Icons.image_not_supported, size: 60, color: Colors.grey),
subtitle: Column( ),
crossAxisAlignment: CrossAxisAlignment.start, const SizedBox(height: 12),
mainAxisSize: MainAxisSize.min, Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text('ID: ${item.lessonId}', style: TextStyle(fontSize: 12, color: Colors.grey[700])), Expanded(
const SizedBox(height: 2), child: Text(
Text( _selectedItem!.lessonName,
item.lessonUrl, style: Theme.of(context).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
style: const TextStyle(fontSize: 12, color: Colors.blueAccent),
overflow: TextOverflow.ellipsis,
maxLines: 2,
), ),
],
), ),
isThreeLine: true, IconButton(
onTap: () { icon: const Icon(Icons.play_circle_fill, size: 40, color: Colors.red),
if (item.lessonUrl.isNotEmpty && (item.lessonUrl.contains('youtube.com') || item.lessonUrl.contains('youtu.be'))) { onPressed: () {
if (_selectedYoutubeUrl != null && _selectedYoutubeUrl!.isNotEmpty) {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => YoutubePlayerPage( builder: (context) => YoutubePlayerPage(lessonUrl: _selectedYoutubeUrl!),
lessonUrl: item.lessonUrl,
// currentBottomNavIndex: _currentBottomNavIndex, // 현재 탭 인덱스 전달
),
), ),
); );
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('유효한 YouTube URL이 아닙니다: ${item.lessonUrl}')), const SnackBar(content: Text('재생할 수 있는 영상이 없습니다.')),
); );
} }
}, },
), ),
); ],
}, ),
const SizedBox(height: 12),
Text(
_selectedItem!.lessonDescription,
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
),
),
],
); );
} }
}, },
), ),
// 2. 하단 바 (BottomNavigationBar) bottomNavigationBar: CustomBottomNavBar(
currentIndex: _currentBottomNavIndex,
onTap: _onBottomNavItemTapped,
),
); );
} }
} }

View File

@@ -1,15 +1,16 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // SystemChrome, DeviceOrientation 사용을 위해 import import 'package:flutter/services.dart'; // SystemChrome, DeviceOrientation 사용을 위해 import
import 'package:youtube_player_flutter/youtube_player_flutter.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart';
import 'common/widgets/custom_bottom_nav_bar.dart';
class YoutubePlayerPage extends StatefulWidget { class YoutubePlayerPage extends StatefulWidget {
final String lessonUrl; final String lessonUrl;
// final int currentBottomNavIndex; final void Function(bool isFullScreen)? onFullScreenToggle;
const YoutubePlayerPage({ const YoutubePlayerPage({
super.key, super.key,
required this.lessonUrl, required this.lessonUrl,
// this.currentBottomNavIndex = 0, this.onFullScreenToggle,
}); });
@override @override
@@ -23,16 +24,12 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
String _videoTitle = 'YouTube Video'; String _videoTitle = 'YouTube Video';
final int _currentBottomNavIndex = 0; final int _currentBottomNavIndex = 0;
bool _isSystemUiVisible = true; bool _isSystemUiVisible = true;
bool _isLoading = true; // 로딩 상태 추가
bool _isFullScreen = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// 페이지 진입 시 기본 화면 방향 설정 (선택적)
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ]);
_videoId = YoutubePlayer.convertUrlToId(widget.lessonUrl); _videoId = YoutubePlayer.convertUrlToId(widget.lessonUrl);
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -59,12 +56,9 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
flags: const YoutubePlayerFlags( flags: const YoutubePlayerFlags(
autoPlay: true, autoPlay: true,
mute: false, mute: false,
// <<< 동영상 재생이 끝나면 컨트롤러를 자동으로 숨기지 않도록 설정 (선택적) >>>
// hideControls: false, // 기본값은 true
), ),
)..addListener(_playerListener); )..addListener(_playerListener);
} else { } else {
print("Error: Could not extract video ID from URL: ${widget.lessonUrl}");
_videoTitle = 'Video Error'; _videoTitle = 'Video Error';
} }
} }
@@ -72,48 +66,30 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
void _playerListener() { void _playerListener() {
if (_controller == null || !mounted) return; if (_controller == null || !mounted) return;
// <<< 재생 상태 감지 >>> if (_isFullScreen != _controller!.value.isFullScreen) {
setState(() {
_isFullScreen = _controller!.value.isFullScreen;
});
widget.onFullScreenToggle?.call(_isFullScreen);
if (_isFullScreen) {
_hideSystemUi();
} else {
_showSystemUi();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
}
if (_controller!.value.playerState == PlayerState.ended) { if (_controller!.value.playerState == PlayerState.ended) {
// 동영상 재생이 완료되었을 때 처리할 로직
print("Video has ended.");
if (mounted) { if (mounted) {
// 전체 화면 모드였다면 해제
if (_controller!.value.isFullScreen) { if (_controller!.value.isFullScreen) {
_controller!.toggleFullScreenMode(); _controller!.toggleFullScreenMode();
} }
// 시스템 UI를 다시 보이도록 설정 (toggleFullScreenMode가 자동으로 처리할 수도 있음)
_showSystemUi();
// 세로 화면으로 복귀 (toggleFullScreenMode가 자동으로 처리할 수도 있음)
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// 필요하다면 페이지를 pop 하거나 다른 동작 수행
// 예: Navigator.of(context).pop();
// 또는 사용자에게 알림 표시
// ScaffoldMessenger.of(context).showSnackBar(
// const SnackBar(content: Text('동영상 재생이 완료되었습니다.')),
// );
} }
return; // ended 상태 처리 후 리스너의 나머지 로직은 건너뛸 수 있음 return;
}
if (_controller!.value.isFullScreen) {
_hideSystemUi();
// 플레이어가 전체 화면으로 진입하면 가로 방향으로 설정 (선택적, 플레이어가 자동으로 할 수 있음)
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.landscapeLeft,
// DeviceOrientation.landscapeRight,
// ]);
} else {
_showSystemUi();
// <<< 전체 화면이 해제되면 화면 방향을 세로로 복구 >>>
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} }
if (_isPlayerReady) { if (_isPlayerReady) {
@@ -174,7 +150,10 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
tabName = 'Statistics'; tabName = 'Statistics';
break; break;
case 3: case 3:
tabName = 'More'; tabName = 'Career'; // New case for Jobs
break;
case 4:
tabName = 'More'; // Updated case for More
break; break;
} }
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -183,6 +162,23 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
} }
} }
@override
void didUpdateWidget(covariant YoutubePlayerPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.lessonUrl != oldWidget.lessonUrl) {
_videoId = YoutubePlayer.convertUrlToId(widget.lessonUrl);
if (_videoId != null) {
_controller?.load(_videoId!); // 새 비디오 로드
} else {
if (mounted) {
setState(() {
_videoTitle = 'Video Error';
});
}
}
}
}
// <<< 뒤로가기 버튼 처리 로직 >>> // <<< 뒤로가기 버튼 처리 로직 >>>
Future<bool> _onWillPop() async { Future<bool> _onWillPop() async {
if (_controller != null && _controller!.value.isFullScreen) { if (_controller != null && _controller!.value.isFullScreen) {
@@ -204,47 +200,11 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
onWillPop: _onWillPop, onWillPop: _onWillPop,
child: Scaffold( child: Scaffold(
extendBodyBehindAppBar: isFullScreen, extendBodyBehindAppBar: isFullScreen,
appBar: isFullScreen
? null body: Column( // <--- Wrap the body content in a Column
: AppBar( children: [
leading: Navigator.canPop(context) Expanded( // <--- Wrap the main content with Expanded
? IconButton( child: Center(
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 child: _controller == null
? Column( ? Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@@ -258,6 +218,7 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
'비디오를 로드할 수 없습니다.\nURL: ${widget.lessonUrl}', '비디오를 로드할 수 없습니다.\nURL: ${widget.lessonUrl}',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
overflow: TextOverflow.ellipsis,
), ),
), ),
], ],
@@ -279,50 +240,18 @@ class _YoutubePlayerPageState extends State<YoutubePlayerPage> {
} }
}); });
} }
print('Player is ready.');
}, },
// <<< 필요하다면 onEnded 콜백 직접 사용 가능 (addListener와 중복될 수 있으니 주의) >>>
// onEnded: (metadata) {
// print("Video has ended (onEnded callback).");
// if (mounted) {
// if (_controller!.value.isFullScreen) {
// _controller!.toggleFullScreenMode();
// }
// _showSystemUi();
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ]);
// }
// },
), ),
), ),
),
],
),
bottomNavigationBar: isFullScreen bottomNavigationBar: isFullScreen
? null ? null
: BottomNavigationBar( : CustomBottomNavBar(
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, currentIndex: _currentBottomNavIndex,
selectedItemColor: Colors.amber[800],
unselectedItemColor: Colors.blue,
onTap: _onBottomNavItemTapped, onTap: _onBottomNavItemTapped,
type: BottomNavigationBarType.fixed,
), ),
), ),
); );