NavigationBar

샤워실의 바보·2024년 2월 9일
0
post-thumbnail
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MainNavigationScreen extends StatefulWidget {
  const MainNavigationScreen({super.key});

  
  State<MainNavigationScreen> createState() => _MainNavigationScreenState();
}

class _MainNavigationScreenState extends State<MainNavigationScreen> {
  int _selectedIndex = 0;

  final screens = [
    const Center(
      child: Text('Home'),
    ),
    const Center(
      child: Text('Search'),
    ),
    const Center(
      child: Text('Home'),
    ),
    const Center(
      child: Text('Search'),
    ),
    const Center(
      child: Text('Search'),
    )
  ];

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

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: screens[_selectedIndex],
      bottomNavigationBar: NavigationBar(
        labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected,
        selectedIndex: _selectedIndex,
        onDestinationSelected: _onTap,
        destinations: const [
          NavigationDestination(
            icon: FaIcon(
              FontAwesomeIcons.house,
              color: Colors.white,
            ),
            label: 'Home',
          ),
          NavigationDestination(
            icon: FaIcon(
              FontAwesomeIcons.magnifyingGlass,
              color: Colors.white,
            ),
            label: 'Search',
          ),
        ],
      ),
    );
  }
}

bottomNavigationBar에서 사용된 NavigationBar는 Material 3에서 제공하는 위젯으로, 하단 탭 네비게이션을 구현할 수 있습니다. 아래는 해당 부분의 코드에 대한 더 자세한 설명입니다.

1. NavigationBar:

bottomNavigationBar: NavigationBar(

NavigationBar 위젯은 Material 3의 하단 네비게이션 바를 만들기 위해 사용됩니다.

2. labelBehavior:

labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected,

labelBehavior는 탭의 라벨이 어떻게 표시될지를 결정합니다. 여기서는 NavigationDestinationLabelBehavior.onlyShowSelected를 사용하여, 오직 선택된 탭의 라벨만 표시됩니다.

3. selectedIndex:

selectedIndex: _selectedIndex,

selectedIndex는 현재 선택된 탭의 인덱스를 나타냅니다. _selectedIndex 변수의 값이 여기에 바인딩됩니다.

4. onDestinationSelected:

onDestinationSelected: _onTap,

onDestinationSelected는 탭이 선택될 때마다 호출되는 콜백 함수입니다. 이 예제에서는 사용자가 탭을 클릭하면 _onTap 함수가 호출됩니다.
매개변수 currentIndex가 onDestinationSelected로 그 명칭이 변화하였습니다.

5. destinations:

destinations: const [

destinationsNavigationDestination 위젯의 리스트를 받아서 각각의 탭을 구성합니다. 각 NavigationDestination은 하나의 탭을 나타냅니다.

6. NavigationDestination:

NavigationDestination(
  icon: FaIcon(
    FontAwesomeIcons.house,
    color: Colors.white,
  ),
  label: 'Home',
),

NavigationDestination은 아이콘과 라벨을 갖는 하나의 탭을 나타냅니다. icon 속성은 해당 탭의 아이콘을 설정합니다. 여기서는 FontAwesome의 아이콘을 사용하고 있으며, label 속성은 해당 탭의 라벨을 설정합니다.

이러한 방식으로, NavigationBar 위젯을 사용하여 하단에 탭 네비게이션 바를 구현할 수 있습니다.

profile
공부하는 개발자

0개의 댓글