bottomNavigationBar를 이용하여 버튼 누르면 페이지가 전환되게 만들어보자
bottomNavigationBar는 onPress(){}가 아닌 onTap(){}을 사용한다.
import 'package:flutter/material.dart';
import './style.dart' as style;
void main() {
runApp(
MaterialApp(
theme: style.theme,
home: MyApp()
)
);
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var tab = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Instagram') ,
actions: [
IconButton(
onPressed: (){},
icon: Icon(Icons.add_box_outlined),
iconSize: 30,
)
],
),
body: [Text('홈페이지'), Text('샵페이지')][tab],
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
currentIndex : tab,
onTap: (i){
setState(() {
tab = i;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
activeIcon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_bag_outlined),
activeIcon: Icon(Icons.shopping_bag),
label: 'Shop',
),
],
),
);
}
}
- 주석이 길어서 그렇지 실제 코드는 몇 줄 안되는데 좋은 퍼포먼스를 보여줌.