BottomNavigationBar in Flutter: solved exercise
If you are looking for BottomNavigationBar in Flutter, this solved exercise gives you a practical implementation pattern you can reuse in real projects.
Problem statement
Build a screen with:
- three tabs: Home, Search, Profile
- keep tab state when switching
- simple tab navigation flow
Flutter solution
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TabsPage()));
class TabsPage extends StatefulWidget {
const TabsPage({super.key});
@override
State<TabsPage> createState() => _TabsPageState();
}
class _TabsPageState extends State<TabsPage> {
int index = 0;
final pages = const [
Center(child: Text('Inicio')),
Center(child: Text('Buscar')),
Center(child: Text('Perfil')),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('BottomNavigationBar')),
body: IndexedStack(index: index, children: pages),
bottomNavigationBar: BottomNavigationBar(
currentIndex: index,
onTap: (i) => setState(() => index = i),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Inicio'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Buscar'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Perfil'),
],
),
);
}
}Expected result
Each tab keeps its state while switching quickly between sections.
Common mistakes
- Rebuilding pages and losing tab state.
- Not syncing
currentIndex. - Mixing tab and stack navigation without design.
Practical use
A common pattern for commerce, media, productivity, and banking-style apps.
Recommended next exercise
- Named Routes in Flutter: solved navigation exercise
- go_router in Flutter: solved navigation exercise
- Flutter Counter with setState: solved exercise step by step
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
How do I keep tab state in Flutter?
Using IndexedStack is one of the most straightforward approaches.
Is BottomNavigationBar still recommended?
Yes, especially for 3 to 5 primary app sections.
What if I have more than 5 sections?
Use a combination of tabs, nested navigation, or a drawer.