Search code examples
fluttermenubottomnavigationview

Flutter BottomNavigationBar never changes highlighted option despite setting 'currentIndex'


I must be having a blond moment here; what I want to do is so simple, but I cannot figure it out.

I have a BottomNavigationBar, and it works just fine for navigating to different pages, but the bottom bar always shows the first item as the current one, it is always the highlighted one.

I am using setState to change the currentIndex, and I can see that is happening, but the bottom bar never changes.

Here is the code:

import 'package:flutter/material.dart';
import 'package:myfestival/models/app_config_model.dart';
import 'package:myfestival/pages/user_mode/menus/user_app_named_routes.dart';

class BottomMenu extends StatefulWidget {
  const BottomMenu({super.key, required this.menus});

  final List<AppMenu> menus;

  @override
  State<BottomMenu> createState() => _BottomMenuState();
}

class _BottomMenuState extends State<BottomMenu> {

  int? currentIndex;

  @override
  Widget build(BuildContext context) {


    print('current index is $currentIndex');

    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: currentIndex??0,
      items: [
        for (final menu in widget.menus.take(5))
          BottomNavigationBarItem(
            icon: menu.smallIcon,
            label: menu.title,
          ),
      ],
      onTap: (value) {
        setState(() {currentIndex = value;});
        UserAppRouter.navigateToMenu(context, widget.menus[value]);
      },
    );
  }
}

And here is the output from clicking the different bottom buttons (I have 3):

current index is null
current index is 2
current index is null
current index is 1
current index is null
current index is 2
current index is null
current index is 0
current index is null
current index is 1
current index is null
current index is 2

But the bottom bar never looks different to this:

enter image description here

(ie. the first item is always the selected one)

What am I missing?

Why won't the highlighted bottom bar option ever change?


Solution

  • The null print is a giveaway that probably every time you call navigation, you don't pass the argument of the current index selected, and because of that, it is always undefined when the widget is drawn.

    One solution could be to make the currentIndex mandatory and use it as an argument, every time you call the widget.

    An alternative is to create a global variable to store the currentIndex and make sure the widget reads on the build call.