MOB.DEV/Flutter
Flutter에 BottomNavigationBar 추가하기
dev.bak
2023. 2. 26. 12:00
반응형
안녕하세요.
이번 포스팅에서는 Flutter에서 BottomNavigationBar 추가하는 방법에 대해서 알아보겠습니다.
BottomNavigationBar를 추가하는 방법은 쉽습니다.
Scaffold에 bottomNavigationBar을 추가해주면 됩니다.
...
home: Scaffold(
...
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '홈',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: '검색',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: '마이페이지',
),
],
),
),
...
위의 코드를 작성하고 실행하면 아래와 같이 보이게 됩니다.
BottomNavigationBar의 탭을 클릭을 했을 때, 해당 하는 탭을 보여주도록 하겠습니다.
선택된 탭의 정보를 저장할 변수와 보여줄 Widget을 저장할 배열을 만들어 줍니다.
class _MyHomePageState extends State<MyHomePage> {
int selectedIndex = 0;
final tabWidgets = [
Center(
child: Text('홈'),
),
Center(
child: Text('검색'),
),
Center(
child: Text('마이페이지'),
),
];
...
}
그리고 Scaffold의 body에 위에 만든 tabWidgets와 selectedIndex를 이용해서 추가해줍니다.
...
return Scaffold(
...
body: tabWidgets[selectedIndex],
...
),
...
그리고 bottomNavigationBar에 탭 메뉴를 탭했을 때 이벤트와 현재 선택된 탭의 index를 추가해줍니다.
class _MyHomePageState extends State<MyHomePage> {
...
void selectTab(int index) {
setState(() {
selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomNavigationBar(
onTap: selectTab,
currentIndex: selectedIndex,
items: [
...
],
...
)
}
}
위의 코드들을 작성하고 확인을 해보면 아래와 같이 보이게 됩니다.
여기까지 부족한 글 읽어주셔서 감사합니다.
제가 잘못 작성한 내용이나 부족한 부분이 있다면 알려주시면 보완 수정하겠습니다.
감사합니다💛
728x90
반응형