티스토리 뷰

이거 탭바라고 자주불렀는데, 플러터에선 BottomNavigationBar라고 하네요.

 

플러터에서 탭바는 상단에 있는 이거라고 합니다.

 

현재 만들 것은 TabBar가 아닌 BottomNavigationBar 입니다.

 

시작

1️⃣ BottomNavgationBar를 이용하기 위해선 StatefulWidget이 필요합니다.

따라서 메인 화면이 될 StatefulWidget을 만들고 루트위젯(MyApp())의 home에 넣어줍니다.

// main.dart
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyWidget(), // home에 Stateful 위젯 넣기
    );
  }
}

// Stateful 위젯 만들기
class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyWidget();
}

class _MyWidget extends State<MyWidget> {

  @override
  Widget build(BuildContext context) {

    return Container(); // 일단 Container 반환
  }
}

 

2️⃣ 기본적인 상중하 구조를 갖추기 위해 Scaffold 위젯으로 바꿔주겠습니다.

class _MyWidget extends State<MyWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold( // Container를 Scaffold로 변경
      appBar: AppBar(
        title: Text('BottomNavigationBar Sample'),
      ),
      body: Center(
      // 메인 컨텐츠 위치
      ),
    );
  }
}

 

3️⃣ Scaffold 속성인 bottomNavigationBar을 추가해주겠습니다. 필수속성인 items에는 탭바요소가 들어가면 되겠습니다.

요소는 반드시 두개 이상이어야 하며 icon과 label은 필수 속성입니다.

class _MyWidget extends State<MyWidget> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('BottomNavigationBar Sample'),
      ),
      body: Center(
      ),
      // bottomNavigationBar 속성 추가 후 탭 요소가 될 item들 추가
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'tab1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.camera),
            label: 'tab2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.usb_rounded),
            label: 'tab3',
          ),
        ],
      ),
    );
  }

 

4️⃣ 이제 bottomNavigationBar가 작동하도록 해주겠습니다.

bottomNavigationBar를 작동시키기 위해서는 인덱스 관리가 필요합니다.

인덱스를 통해 어떤 탭 화면에 위치하고 있는지 관찰하고 화면을 업데이트 할 것입니다.

 

먼저 클래스 변수로 인덱스를 저장할 변수를 선언해줍니다. (_selectedIndex)

그리고 인덱스가 바뀔때마다 변수를 변경해줄 _onItemTapped 함수도 만들어줍니다.

ㄴ 함수명은 변경해도 되나, 파라미터는 변경할 수 없습니다.

class _MyWidget extends State<MyWidget> {
  // 현재 선택된 탭 인덱스 관리할 변수
  int _selectedIndex = 0; 

  // 탭 될때 인덱스 변수 변경할 함수
  void _onItemTapped(int index) { 
    setState(() {
      _selectedIndex = index;
    });
  }
  
  ...

 

그 다음 BottomNavigationBar에 다음 속성들을 추가해줍니다.

currentIndex: _selectedIndex, // 현재 인덱스를 _selectedIndex에 저장
onTap: _onItemTapped, // 요소(item)을 탭 할 시 실행

 

5️⃣ 작동 확인을 위해 Scaffold 위젯의 body에 텍스트를 넣어주었습니다.

body: Center(
	child: Text("${_selectedIndex}", style: TextStyle(fontSize: 50)),
),

탭별로 위젯 넣기 ⬇️

더보기

이런식으로 위젯 리스트를 선언해놓고 return문에 작성하면 더 깔끔한 코드를 작성할 수 있습니다.

// 탭 별 페이지 - 클래스 변수
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      '0',
      style: optionStyle,
    ),
    Text(
      '1',
      style: optionStyle,
    ),
    Text(
      '2',
      style: optionStyle,
    ),
  ];
  
  ...
  
  // Scaffold body
body: Center(
    child: _widgetOptions.elementAt(_selectedIndex),
),

 

결과

 

전체코드

더보기
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyWidget();
}

class _MyWidget extends State<MyWidget> {
  int _selectedIndex = 0;

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

// 탭 별 페이지
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      '0',
      style: optionStyle,
    ),
    Text(
      '1',
      style: optionStyle,
    ),
    Text(
      '2',
      style: optionStyle,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'tab1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.camera),
            label: 'tab2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.usb_rounded),
            label: 'tab3',
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
  }
}

 

 

 


 

Ref.

Flutter BottomNavigationBar 공식문서

 

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

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함