import 'package:flutter/material.dart' ;
import 'package:navigationbar_example/view/tabs/home_screen.dart' ;
import 'package:navigationbar_example/view/tabs/notifications_screen.dart' ;
import 'package:navigationbar_example/view/tabs/profile_screen.dart' ;
import 'package:navigationbar_example/view/tabs/search_screen.dart' ;
class MainPage extends StatefulWidget {
const MainPage ({ super .key});
@override
MainPageState createState () => MainPageState ();
}
class MainPageState extends State < MainPage > {
int _currentIndex = 0 ; // 현재 선택된 탭의 인덱스
final List < GlobalKey < NavigatorState >> _navigatorKeys = [
GlobalKey < NavigatorState >(),
GlobalKey < NavigatorState >(),
GlobalKey < NavigatorState >(),
GlobalKey < NavigatorState >(),
];
void _onTap ( int index) {
if (index == _currentIndex) {
_navigatorKeys[index].currentState ? . popUntil ((route) => route.isFirst);
} else {
setState (() {
_currentIndex = index;
});
}
}
// 각 탭에서 보여줄 화면 리스트(비워져 있음)
final List < Widget > _pages = [];
@override // 각 탭에 보여줄 화면을 생성(onTap 함수를 전달)
void initState () {
super . initState ();
_pages. addAll ([
const HomeScreen (),
const SearchScreen (),
NotificationsScreen (onTap : _onTap),
ProfileScreen (),
]);
}
@override
Widget build ( BuildContext context) {
return Scaffold (
body : IndexedStack (
index : _currentIndex,
children : List . generate (_pages.length, (index) {
return Navigator (
key : _navigatorKeys[index],
onGenerateRoute : (routeSettings) {
return MaterialPageRoute (
builder : (context) => _pages[index],
);
},
);
}),
), // 선택된 탭의 화면을 보여줄 위젯
bottomNavigationBar : BottomNavigationBar (
currentIndex : _currentIndex, // 선택된 탭 인덱스
onTap : _onTap, // 탭 선택 시 호출할 함수
items : const [
BottomNavigationBarItem (
icon : Icon ( Icons .home),
label : 'Home' ,
),
BottomNavigationBarItem (
icon : Icon ( Icons .search),
label : 'Search' ,
),
BottomNavigationBarItem (
icon : Icon ( Icons .notifications),
label : 'Notifications' ,
),
BottomNavigationBarItem (
icon : Icon ( Icons .person),
label : 'Profile' ,
),
],
selectedItemColor : Colors .blue, // 선택된 아이템 색상
unselectedItemColor : Colors .grey, // 선택되지 않은 아이템 색상
),
);
}
}