BottomNavigationBar in Flutter: solved exercise with IndexedStack

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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.

Guided practice and next step

FAQ

How do I keep tab state in Flutter?

Using IndexedStack is one of the most straightforward approaches.

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.