Using the BottomNavigationBar Widget in Flutter

In Flutter, the BottomNavigationBar widget is a fundamental component for creating a seamless and intuitive navigation experience within your app. It’s designed to display a set of icons or text labels at the bottom of the screen, allowing users to quickly switch between different sections of your application.

What is the BottomNavigationBar Widget?

The BottomNavigationBar is a widget in Flutter that is used to display a bottom navigation bar, typically with 3-5 items, allowing users to easily navigate between different sections of the app. It provides a persistent and easily accessible way to switch views, enhancing the user experience.

Why Use the BottomNavigationBar?

  • Improved Navigation: Provides a clear and accessible way for users to switch between different sections.
  • User Experience: Enhances usability by keeping navigation controls consistently visible.
  • Best Practices: Aligns with mobile UI/UX design principles, providing a familiar navigation pattern.

How to Implement the BottomNavigationBar Widget in Flutter

To implement a BottomNavigationBar in Flutter, follow these steps:

Step 1: Set Up Your Flutter Project

Ensure you have Flutter installed and your development environment is properly configured. You can create a new Flutter project using the following command:

flutter create bottom_navigation_example
cd bottom_navigation_example

Step 2: Add the BottomNavigationBar to Your Scaffold

The BottomNavigationBar is typically placed inside the bottomNavigationBar property of a Scaffold widget. The Scaffold provides the basic layout structure for your app’s pages.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bottom Navigation Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  int _currentIndex = 0;

  final List<Widget> _children = [
    PlaceholderWidget(Colors.white),
    PlaceholderWidget(Colors.deepOrange),
    PlaceholderWidget(Colors.green)
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Navigation Example'),
      ),
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.mail),
            label: 'Messages',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile'
          )
        ],
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

class PlaceholderWidget extends StatelessWidget {
  final Color color;

  PlaceholderWidget(this.color);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
    );
  }
}

In this example:

  • The MyHomePage class is a stateful widget that manages the currently selected tab index.
  • _currentIndex holds the index of the currently selected tab.
  • _children is a list of widgets that are displayed based on the selected tab.
  • BottomNavigationBar is added to the bottomNavigationBar property of the Scaffold.
  • onTap is a callback function that updates the _currentIndex when a tab is tapped.
  • currentIndex binds the _currentIndex state to the BottomNavigationBar.
  • items is a list of BottomNavigationBarItem widgets, each representing a tab.

Step 3: Customize the BottomNavigationBar

You can customize the appearance and behavior of the BottomNavigationBar using various properties:

BottomNavigationBar(
  backgroundColor: Colors.grey[200],
  selectedItemColor: Colors.amber[800],
  unselectedItemColor: Colors.grey,
  selectedFontSize: 14,
  unselectedFontSize: 12,
  iconSize: 30,
  onTap: onTabTapped,
  currentIndex: _currentIndex,
  type: BottomNavigationBarType.fixed,
  items: [
    BottomNavigationBarItem(
      icon: new Icon(Icons.home),
      label: 'Home',
    ),
    BottomNavigationBarItem(
      icon: new Icon(Icons.mail),
      label: 'Messages',
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.person),
      label: 'Profile'
    )
  ],
)
  • backgroundColor: Sets the background color of the navigation bar.
  • selectedItemColor: Sets the color of the selected item.
  • unselectedItemColor: Sets the color of the unselected items.
  • selectedFontSize: Sets the font size of the selected item’s label.
  • unselectedFontSize: Sets the font size of the unselected items’ labels.
  • iconSize: Sets the size of the icons.
  • type: Defines how the navigation bar should behave. BottomNavigationBarType.fixed displays all labels, while BottomNavigationBarType.shifting animates the selected item.

Step 4: Handling Navigation

The onTap callback function updates the _currentIndex, which is then used to determine which widget to display in the body of the Scaffold. In the _MyHomePageState, this is done as follows:

void onTabTapped(int index) {
  setState(() {
    _currentIndex = index;
  });
}

BottomNavigationBar Types: Fixed vs. Shifting

The BottomNavigationBar has two types:

  • Fixed: When type is set to BottomNavigationBarType.fixed, all labels are always visible, and the selected item changes color.
  • Shifting: When type is set to BottomNavigationBarType.shifting, the selected item expands and shows its label, while the other items might shift or change in size. The backgroundColor of the BottomNavigationBarItem can be used to provide a background color for each item when using the shifting type.

Here is an example of using the shifting type:

BottomNavigationBar(
  onTap: onTabTapped,
  currentIndex: _currentIndex,
  type: BottomNavigationBarType.shifting,
  items: [
    BottomNavigationBarItem(
      icon: new Icon(Icons.home),
      label: 'Home',
      backgroundColor: Colors.blue
    ),
    BottomNavigationBarItem(
      icon: new Icon(Icons.mail),
      label: 'Messages',
      backgroundColor: Colors.red
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.person),
      label: 'Profile',
      backgroundColor: Colors.green
    )
  ],
)

Best Practices for Using BottomNavigationBar

  • Keep It Simple: Limit the number of items to 3-5 for optimal usability.
  • Clear Icons and Labels: Use recognizable icons and clear labels.
  • Consistent UI: Maintain consistency in design and functionality.
  • Accessibility: Ensure your navigation bar is accessible, with sufficient contrast and appropriate sizing.

Conclusion

The BottomNavigationBar widget is an essential tool for building navigable and user-friendly Flutter applications. By following the steps outlined above and adhering to best practices, you can effectively integrate this widget to improve the user experience of your app. Whether you choose a fixed or shifting navigation bar, remember to focus on creating an intuitive and accessible interface for your users.