How to add Bottom Navigation Bar in Flutter
2 min readFeb 4, 2023
In Flutter, you can use the BottomNavigationBar
widget to create a bottom navigation bar. Here's an example of how to use it:
import 'package:flutter/material.dart';
import '../dashboard/home.dart';
import 'testfolder/screen1.dart';
class MyNavigation extends StatefulWidget {
const MyNavigation({super.key});
@override
State<MyNavigation> createState() => _MyNavigationState();
}
class _MyNavigationState extends State<MyNavigation> {
// default index
int index = 0;
// screen lists
final screens = [ const MyHome(), const MyTest(), ];
@override
Widget build(BuildContext context) {
return Scaffold(
body: screens[index],
bottomNavigationBar: NavigationBarTheme(
data: NavigationBarThemeData(
indicatorColor: Colors.red.shade400,
labelTextStyle: MaterialStateProperty.all(
const TextStyle(fontSize: 12),
),
),
child: NavigationBar(
selectedIndex: index,
onDestinationSelected: (index) => setState(() {
this.index = index;
}),
height: 60.0,
backgroundColor: Colors.red,
// to hide labels
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
animationDuration: const Duration(seconds: 3),
destinations: const [
NavigationDestination(
icon: Icon(Icons.home_outlined),
selectedIcon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.delivery_dining_outlined),
selectedIcon: Icon(Icons.delivery_dining),
label: 'Delivery',
),
]),
),
);
}
}
In this example, the BottomNavigationBar
is added to the Scaffold
widget, which provides a default layout structure. The BottomNavigationBar
takes a list of NavigationDestination
widgets as its destinations
property, each of which represents a navigation item with an icon and a title. The selectedIndex
property is used to keep track of the selected item, and the onDestinationSelected
a callback is called when the user taps on a navigation item.