welcome to my blog

[Flutter] BottomNavigation 본문

Flutter

[Flutter] BottomNavigation

_annie_ 2021. 10. 21. 20:00
728x90

 

Scaffold -> bottomNavigationBar :

BottomNavigationBar 추가

 

BottomNavigationBar -> items :

BottomNavigationBarItem 추가

 

* 4개 이상일때만 애니메이션 적용됨 (3개로 해놓고 왜 안되나 한참 삽질함..)

 

<전체 코드>

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: _widgetOptions.elementAt(_selectedIndex),
        ),
        backgroundColor: Color(0xff2d2680),
        bottomNavigationBar: BottomNavigationBar(
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
              backgroundColor: Colors.red,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.business),
              label: 'Business',
              backgroundColor: Colors.green,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              label: 'School',
              backgroundColor: Colors.purple,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.settings),
              label: 'Setting',
              backgroundColor: Colors.pink,
            ),
          ],
          currentIndex: _selectedIndex,
          selectedItemColor: Colors.amber[800],
          onTap: _onItemTapped,
        ),
      ),
    );
  }

 

onTap : BottomNavigation이 선택되었을때 

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

_selectedIndex의 값을 index 값으로 업데이트

 

 _widgetOptions.elementAt(_selectedIndex),

_widgetOptions에서 해당하는 index의 항목을 가져옴

 

static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static final List<Widget> _widgetOptions = [
    NewsHomeApp(),
    const Text('Index 0: Business', style: optionStyle),
    const Text('Index 1: School', style: optionStyle),
    const Text('Index 2: Setting', style: optionStyle),
  ];

 

첫번째 widget : custom위젯

2, 3, 4번째 widget : Text 

 

결과화면 :

 

 

 

아이콘을 선택하면 설정해두었던 색상으로 변경된다.

4개 이상이기 때문에 애니메이션 효과도 같이 적용된다.

 

참고 :

https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html

 

BottomNavigationBar class - material library - Dart API

A material widget that's displayed at the bottom of an app for selecting among a small number of views, typically between three and five. The bottom navigation bar consists of multiple items in the form of text labels, icons, or both, laid out on top of a

api.flutter.dev

 

728x90
반응형