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:
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:
Explanation of the Code:
StatefulWidget: We use a
StatefulWidget(BottomNavExample) because we need to update the state when the user selects a new tab._selectedIndex: This integer keeps track of the currently selected tab. Initially, it's set to
0(Home tab)._widgetOptions: A list of widgets that correspond to the content of each page (Home, Search, and Profile).
_onItemTapped: This function updates the
_selectedIndexwhenever the user taps on a tab.BottomNavigationBar:
currentIndex: This property sets the selected tab based on_selectedIndex.onTap: This callback is triggered when a tab is selected, calling the_onItemTappedmethod.items: This list defines the tabs and their icons (Home, Search, and Profile).
Step 3: Run the App
Run your Flutter app:
You should see a simple app with a BottomNavigationBar that allows you to switch between the Home, Search, and Profile pages.

Comments
Post a Comment