Search code examples
flutterdartflutter-layoutflutter-dependenciesflutter-bottomnavigation

I want to change container color but it doesn't work?


when i press the bottomnavigationbar item why it doesnt work

Here the codes;

    Color? color;
  colorChange() {
    if (_pageIndex == 0) {
      color = AppColors.buttonColor;
    }
    if (_pageIndex == 1) {
      color = AppColors.buttonColor;
    }
    if (_pageIndex == 2) {
      color = AppColors.buttonColor;
    }

    return null;
  }

BottomNavBar item section,

items: [
            BottomNavigationBarItem(
                icon: Padding(
                  padding: context.paddingTop / 8,
                  child: Container(
                    height: 40,
                    decoration: BoxDecoration(
                        color: colorChange(),
                        borderRadius: BorderRadius.circular(30)),
                    width: 40,
                    child: const Icon(
                      Icons.home_outlined,
                    ),
                  ),
                ),
                label: ''),

Solution

  • This method isn't returning any color but retuns a null at the end.

    Try this:

    Color? color;
      Color colorChange(currentIndex) {
        if (currentIndex == _pageIndex) 
       {
          color = AppColors.buttonColor;
        }
        else{
          color = Colors.transparent;
        }
        return color;
      }
    

    And in bottom Navigation bar item:

    items: [
                BottomNavigationBarItem(
                    icon: Padding(
                      padding: context.paddingTop / 8,
                      child: Container(
                        height: 40,
                        decoration: BoxDecoration(
                            color: colorChange(0),//here pass the index
                            borderRadius: BorderRadius.circular(30)),
                        width: 40,
                        child: const Icon(
                          Icons.home_outlined,
                        ),
                      ),
                    ),
                    label: ''),