How to Implement BottomNavigationBar in Flutter

This guide will walk you through creating a simple app in Flutter with a BottomNavigationBar, allowing users to switch between different pages. The BottomNavigationBar is a commonly used widget in mobile apps for easy navigation between top-level views. This tutorial will provide a step-by-step approach, from setting up a new Flutter project to adding the BottomNavigationBar functionality, complete with icons and content for each tab.

By the end of this guide, you'll have a working Flutter app where users can switch between three pages: Home, Search, and Profile, using the bottom navigation bar. Whether you're new to Flutter or just need a refresher, this guide covers all the essentials to get you up and running!


Step 1: Create a New Flutter Project

First, create a new Flutter project if you don't already have one:

flutter create bottom_nav_example
cd bottom_nav_example

Step 2: Update lib/main.dart

Open the main.dart file in your project and modify it to include a BottomNavigationBar. Here’s a simple example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BottomNavExample(),
    );
  }
}

class BottomNavExample extends StatefulWidget {
  @override
  _BottomNavExampleState createState() => _BottomNavExampleState();
}

class _BottomNavExampleState extends State<BottomNavExample> {
  int _selectedIndex = 0;

  // List of pages to show when a tab is selected
  static const List<Widget> _widgetOptions = <Widget>[
    Text('Home Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('Search Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
    Text('Profile Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
  ];

  // Method to handle the tab changes
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Navigation Bar Example'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex), // Display the selected page
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex, // Set the selected index
        onTap: _onItemTapped, // Handle tab change
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Search',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

Explanation of the Code:

  1. StatefulWidget: We use a StatefulWidget (BottomNavExample) because we need to update the state when the user selects a new tab.

  2. _selectedIndex: This integer keeps track of the currently selected tab. Initially, it's set to 0 (Home tab).

  3. _widgetOptions: A list of widgets that correspond to the content of each page (Home, Search, and Profile).

  4. _onItemTapped: This function updates the _selectedIndex whenever the user taps on a tab.

  5. BottomNavigationBar:

    • currentIndex: This property sets the selected tab based on _selectedIndex.
    • onTap: This callback is triggered when a tab is selected, calling the _onItemTapped method.
    • items: This list defines the tabs and their icons (Home, Search, and Profile).

Step 3: Run the App

Run your Flutter app:

flutter run

You should see a simple app with a BottomNavigationBar that allows you to switch between the Home, Search, and Profile pages.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example