Tabs With a Navigation Bar
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 23 of 33.
Many apps keep their main pages in tabs along the bottom of the screen. NavigationBar draws them; you give it to the Scaffold's bottomNavigationBar:.
NavigationBar(
selectedIndex: index,
onDestinationSelected: (int i) {
setState(() {
index = i;
});
},
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
)Each NavigationDestination is one tab, with an icon and a label. selectedIndex says which tab is highlighted, counting from 0. When a tab is tapped, onDestinationSelected gets its index.
The bar does not remember the tab by itself: you keep index in your state and change it with setState. The body shows the page for that index, here pages[index] from a list of widgets.
Challenge
EasyThe bar has three tabs, but tapping them does nothing. Add onDestinationSelected: so a tapped tab is highlighted and its page shows: Favorites page for Favorites, Settings page for Settings.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int index = 0;
final List<Widget> pages = const [
Center(child: Text('Home page')),
Center(child: Text('Favorites page')),
Center(child: Text('Settings page')),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('My App')),
body: pages[index],
bottomNavigationBar: NavigationBar(
selectedIndex: index,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.favorite), label: 'Favorites'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler