본문 바로가기
개발/플러터

[플러터] BottomNavigationBar 에 대해서

by 핸디(Handy) 2020. 5. 2.

BottomNavigationBar 은 하단에 메뉴탭을 구성하는 위젯입니다. 

class MyFirstWidget extends StatelessWidget {
  MyFirstWidget({Key key}) : super(key: key);
  int _selectedIndex = 0;
  static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
  ];

  void _onItemTapped(int index) {
    _selectedIndex = index;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.green,
        onTap: _onItemTapped,
        type: BottomNavigationBarType.shifting,
        unselectedItemColor : Colors.red
      ),
    );
  }
}

bottomNavigationBar 위젯을 만들고 그 안에 item를 넣는 방식으로 이루어집니다.
위의 코드에서는 item을 클릭하면 onTap -> _inItemTapped가 실행되고 해당 텍스트가 옵션을 가지고 body에 표현되는 구조입니다.

bottomNavigationBar의 구현

BottomNavigationBar(
{Key key,
@required List<BottomNavigationBarItem> items,
ValueChanged<int> onTap,
int currentIndex: 0,
double elevation: 8.0,
BottomNavigationBarType type,
Color fixedColor,
Color backgroundColor,
double iconSize: 24.0,
Color selectedItemColor,
Color unselectedItemColor,
IconThemeData selectedIconTheme: const IconThemeData(),
IconThemeData unselectedIconTheme: const IconThemeData(),
double selectedFontSize: 14.0,
double unselectedFontSize: 12.0,
TextStyle selectedLabelStyle,
TextStyle unselectedLabelStyle,
bool showSelectedLabels: true,
bool showUnselectedLabels}
)

currentIndex : 현재 select된 bar item의 index, 0부터 시작
BottomNavigationBarType : select된 item의 영역 지정. fixed, shifting, value 가 있음.
onTap : 클릭 이벤트

item의 구현은 다음과 같습니다.

const BottomNavigationBarItem({
  @required this.icon,
  this.title,
  Widget activeIcon,
  this.backgroundColor,
}) : activeIcon = activeIcon ?? icon,
     assert(icon != null);

icon : 하단바에 들어갈 아이콘 ( 필수 )
activeIcon : 해당 아이콘이 select 됬을때 보일 아이콘

댓글