How can I hide a BottomNavigationBarItem on Flutter?

I have something like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> int _selectedIndex = 0;
final List<Widget> _screens = const [
TopNavigator(),
SearchScreen(),
SettingsScreen(),
SelectedAlbumScreen()
];
void setSelectedScreen(int index) {
setState(() {
_selectedIndex = index;
});
}
BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.black,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
],
currentIndex: _selectedIndex,
selectedItemColor: Theme.of(context).primaryColor,
unselectedItemColor: Colors.grey,
onTap: (int index) {
setSelectedScreen(index);
},
),
</code>
<code> int _selectedIndex = 0; final List<Widget> _screens = const [ TopNavigator(), SearchScreen(), SettingsScreen(), SelectedAlbumScreen() ]; void setSelectedScreen(int index) { setState(() { _selectedIndex = index; }); } BottomNavigationBar( type: BottomNavigationBarType.fixed, backgroundColor: Colors.black, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem( icon: Icon(Icons.search), label: 'Search'), BottomNavigationBarItem( icon: Icon(Icons.settings), label: 'Settings'), ], currentIndex: _selectedIndex, selectedItemColor: Theme.of(context).primaryColor, unselectedItemColor: Colors.grey, onTap: (int index) { setSelectedScreen(index); }, ), </code>
  int _selectedIndex = 0;

  final List<Widget> _screens = const [
    TopNavigator(),
    SearchScreen(),
    SettingsScreen(),
    SelectedAlbumScreen()
  ];

  void setSelectedScreen(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }


 BottomNavigationBar(
                      type: BottomNavigationBarType.fixed,
                      backgroundColor: Colors.black,
                      items: const <BottomNavigationBarItem>[
                        BottomNavigationBarItem(
                            icon: Icon(Icons.home), label: 'Home'),
                        BottomNavigationBarItem(
                            icon: Icon(Icons.search), label: 'Search'),
                        BottomNavigationBarItem(
                            icon: Icon(Icons.settings), label: 'Settings'),
                      ],
                      currentIndex: _selectedIndex,
                      selectedItemColor: Theme.of(context).primaryColor,
                      unselectedItemColor: Colors.grey,
                      onTap: (int index) {
                        setSelectedScreen(index);
                      },
                    ),

As you can see, I have 4 screens in my list, but only 3 declared in my BottomNavigationBar, so I need to have those 4 screens available to go to them but the number 4 must be hidden for the user so that it can only be accessed by tapping on some button.

When I switch to the screen via code, I get an assertion error.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>GestureDetector(
onTap: () {
context.read<HandleBottomNavigationIndex>().setSelectedScreen(3);
}
</code>
<code>GestureDetector( onTap: () { context.read<HandleBottomNavigationIndex>().setSelectedScreen(3); } </code>
GestureDetector(
            onTap: () {
              context.read<HandleBottomNavigationIndex>().setSelectedScreen(3);
            }

Failed assertion: line 251 pos 15: '0 <= currentIndex && currentIndex < items.length': is not true.

3

Try below code…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>bool showItem = true;
void setSelectedScreen(int index) {
if (index >= 0 && index < _screens.length) {
setState(() {
_selectedIndex = index;
});
}
}
List<BottomNavigationBarItem> get _visibleItems {
final items = <BottomNavigationBarItem>[
const BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
const BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
const BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
if (showItem)
const BottomNavigationBarItem(
icon: Icon(Icons.album),
label: 'Album',
),
];
return items;
}
</code>
<code>bool showItem = true; void setSelectedScreen(int index) { if (index >= 0 && index < _screens.length) { setState(() { _selectedIndex = index; }); } } List<BottomNavigationBarItem> get _visibleItems { final items = <BottomNavigationBarItem>[ const BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), const BottomNavigationBarItem( icon: Icon(Icons.search), label: 'Search', ), const BottomNavigationBarItem( icon: Icon(Icons.settings), label: 'Settings', ), if (showItem) const BottomNavigationBarItem( icon: Icon(Icons.album), label: 'Album', ), ]; return items; } </code>
bool showItem = true;

void setSelectedScreen(int index) {
    if (index >= 0 && index < _screens.length) {
      setState(() {
        _selectedIndex = index;
      });
    }
  }

List<BottomNavigationBarItem> get _visibleItems {
final items = <BottomNavigationBarItem>[
  const BottomNavigationBarItem(
    icon: Icon(Icons.home),
    label: 'Home',
  ),
  const BottomNavigationBarItem(
    icon: Icon(Icons.search),
    label: 'Search',
  ),
  const BottomNavigationBarItem(
    icon: Icon(Icons.settings),
    label: 'Settings',
  ),
  if (showItem)
    const BottomNavigationBarItem(
      icon: Icon(Icons.album), 
      label: 'Album',
    ),
];
return items;
 }

And in your build method

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>final visibleScreens = showItem
? _screens
: _screens.sublist(0, 3);
body: visibleScreens[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.black,
items: _visibleItems,
currentIndex: _selectedIndex,
selectedItemColor: Theme.of(context).primaryColor,
unselectedItemColor: Colors.grey,
onTap: (int index) {
setSelectedScreen(index);
},
),
</code>
<code>final visibleScreens = showItem ? _screens : _screens.sublist(0, 3); body: visibleScreens[_selectedIndex], bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, backgroundColor: Colors.black, items: _visibleItems, currentIndex: _selectedIndex, selectedItemColor: Theme.of(context).primaryColor, unselectedItemColor: Colors.grey, onTap: (int index) { setSelectedScreen(index); }, ), </code>
final visibleScreens = showItem
        ? _screens
        : _screens.sublist(0, 3); 

body: visibleScreens[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.black,
        items: _visibleItems,
        currentIndex: _selectedIndex,
        selectedItemColor: Theme.of(context).primaryColor,
        unselectedItemColor: Colors.grey,
        onTap: (int index) {
          setSelectedScreen(index);
        },
      ),

Change showItem true/false as your requirement in setState

2

It seems that by the very nature of the BottomNavigationBar it is impossible to have a number of screens different from the number of items in the BottomNavigationBar.

but I was able to solve it just by creating my own BottomNavigationBar.

here is the code:

item:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import 'package:flutter/material.dart';
class CustomBottomNavigationBarItem {
final IconData icon;
final String label;
const CustomBottomNavigationBarItem(
{required this.icon, required this.label});
}
</code>
<code>import 'package:flutter/material.dart'; class CustomBottomNavigationBarItem { final IconData icon; final String label; const CustomBottomNavigationBarItem( {required this.icon, required this.label}); } </code>
import 'package:flutter/material.dart';

class CustomBottomNavigationBarItem {
  final IconData icon;
  final String label;

  const CustomBottomNavigationBarItem(
      {required this.icon, required this.label});
}

BottomNavigatonBar:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import 'package:flutter/material.dart';
import 'package:palm_player/presentation/widgets/bottom_navigator/custom_bottom_navigation_bar_item.dart';
class CustomBottomNavigationBar extends StatefulWidget {
final List<CustomBottomNavigationBarItem> items;
final void Function(int index) onTap;
final int selectedIndex;
final Color? selectedItemColor;
final Color? unselectedItemColor;
final Color? backgroundColor;
const CustomBottomNavigationBar(
{super.key,
required this.items,
required this.onTap,
required this.selectedIndex,
this.backgroundColor = Colors.white,
this.selectedItemColor = Colors.black,
this.unselectedItemColor = Colors.grey})
: assert(items.length >= 2);
@override
State<CustomBottomNavigationBar> createState() =>
_CustomBottomNavigationBarState();
}
class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
@override
Widget build(BuildContext context) {
const double bottomNavigationBarHeight =
kBottomNavigationBarHeight + (kBottomNavigationBarHeight * 0.2);
return Container(
height: bottomNavigationBarHeight,
decoration: BoxDecoration(color: widget.backgroundColor),
padding: const EdgeInsets.only(top: 10),
child: Row(
children: [
const Spacer(),
...widget.items.asMap().entries.map((currentItem) => Expanded(
child: InternalItem(
icon: currentItem.value.icon,
label: currentItem.value.label,
onTap: widget.onTap,
index: currentItem.key,
color: widget.selectedIndex == currentItem.key
? widget.selectedItemColor!
: widget.unselectedItemColor!,
))),
const Spacer()
],
),
);
}
}
class InternalItem extends StatelessWidget {
final int index;
final IconData icon;
final String label;
final Color color;
final void Function(int index) onTap;
const InternalItem(
{super.key,
required this.icon,
required this.label,
required this.onTap,
required this.index,
required this.color});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
onTap(index);
},
child: Column(
children: [
Icon(
icon,
color: color,
),
Text(
label,
style: TextStyle(color: color, fontSize: 11),
)
],
),
);
}
}
</code>
<code>import 'package:flutter/material.dart'; import 'package:palm_player/presentation/widgets/bottom_navigator/custom_bottom_navigation_bar_item.dart'; class CustomBottomNavigationBar extends StatefulWidget { final List<CustomBottomNavigationBarItem> items; final void Function(int index) onTap; final int selectedIndex; final Color? selectedItemColor; final Color? unselectedItemColor; final Color? backgroundColor; const CustomBottomNavigationBar( {super.key, required this.items, required this.onTap, required this.selectedIndex, this.backgroundColor = Colors.white, this.selectedItemColor = Colors.black, this.unselectedItemColor = Colors.grey}) : assert(items.length >= 2); @override State<CustomBottomNavigationBar> createState() => _CustomBottomNavigationBarState(); } class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> { @override Widget build(BuildContext context) { const double bottomNavigationBarHeight = kBottomNavigationBarHeight + (kBottomNavigationBarHeight * 0.2); return Container( height: bottomNavigationBarHeight, decoration: BoxDecoration(color: widget.backgroundColor), padding: const EdgeInsets.only(top: 10), child: Row( children: [ const Spacer(), ...widget.items.asMap().entries.map((currentItem) => Expanded( child: InternalItem( icon: currentItem.value.icon, label: currentItem.value.label, onTap: widget.onTap, index: currentItem.key, color: widget.selectedIndex == currentItem.key ? widget.selectedItemColor! : widget.unselectedItemColor!, ))), const Spacer() ], ), ); } } class InternalItem extends StatelessWidget { final int index; final IconData icon; final String label; final Color color; final void Function(int index) onTap; const InternalItem( {super.key, required this.icon, required this.label, required this.onTap, required this.index, required this.color}); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { onTap(index); }, child: Column( children: [ Icon( icon, color: color, ), Text( label, style: TextStyle(color: color, fontSize: 11), ) ], ), ); } } </code>
import 'package:flutter/material.dart';
import 'package:palm_player/presentation/widgets/bottom_navigator/custom_bottom_navigation_bar_item.dart';

class CustomBottomNavigationBar extends StatefulWidget {
  final List<CustomBottomNavigationBarItem> items;
  final void Function(int index) onTap;
  final int selectedIndex;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;
  final Color? backgroundColor;

  const CustomBottomNavigationBar(
      {super.key,
      required this.items,
      required this.onTap,
      required this.selectedIndex,
      this.backgroundColor = Colors.white,
      this.selectedItemColor = Colors.black,
      this.unselectedItemColor = Colors.grey})
      : assert(items.length >= 2);

  @override
  State<CustomBottomNavigationBar> createState() =>
      _CustomBottomNavigationBarState();
}

class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
  @override
  Widget build(BuildContext context) {
    const double bottomNavigationBarHeight =
        kBottomNavigationBarHeight + (kBottomNavigationBarHeight * 0.2);
    return Container(
      height: bottomNavigationBarHeight,
      decoration: BoxDecoration(color: widget.backgroundColor),
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        children: [
          const Spacer(),
          ...widget.items.asMap().entries.map((currentItem) => Expanded(
                  child: InternalItem(
                icon: currentItem.value.icon,
                label: currentItem.value.label,
                onTap: widget.onTap,
                index: currentItem.key,
                color: widget.selectedIndex == currentItem.key
                    ? widget.selectedItemColor!
                    : widget.unselectedItemColor!,
              ))),
          const Spacer()
        ],
      ),
    );
  }
}

class InternalItem extends StatelessWidget {
  final int index;
  final IconData icon;
  final String label;
  final Color color;
  final void Function(int index) onTap;
  const InternalItem(
      {super.key,
      required this.icon,
      required this.label,
      required this.onTap,
      required this.index,
      required this.color});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        onTap(index);
      },
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
          ),
          Text(
            label,
            style: TextStyle(color: color, fontSize: 11),
          )
        ],
      ),
    );
  }
}


implementation:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>CustomBottomNavigationBar(
selectedItemColor: Theme.of(context).primaryColor,
selectedIndex: _selectedIndex,
backgroundColor: Colors.black,
items: const <CustomBottomNavigationBarItem>[
CustomBottomNavigationBarItem(
icon: Icons.home, label: 'Home'),
CustomBottomNavigationBarItem(
icon: Icons.search, label: 'Search'),
CustomBottomNavigationBarItem(
icon: Icons.settings, label: 'Settings')
],
onTap: (int index) {
setSelectedScreen(index);
},
),
```
</code>
<code>CustomBottomNavigationBar( selectedItemColor: Theme.of(context).primaryColor, selectedIndex: _selectedIndex, backgroundColor: Colors.black, items: const <CustomBottomNavigationBarItem>[ CustomBottomNavigationBarItem( icon: Icons.home, label: 'Home'), CustomBottomNavigationBarItem( icon: Icons.search, label: 'Search'), CustomBottomNavigationBarItem( icon: Icons.settings, label: 'Settings') ], onTap: (int index) { setSelectedScreen(index); }, ), ``` </code>
CustomBottomNavigationBar(
                      selectedItemColor: Theme.of(context).primaryColor,
                      selectedIndex: _selectedIndex,
                      backgroundColor: Colors.black,
                      items: const <CustomBottomNavigationBarItem>[
                        CustomBottomNavigationBarItem(
                            icon: Icons.home, label: 'Home'),
                        CustomBottomNavigationBarItem(
                            icon: Icons.search, label: 'Search'),
                        CustomBottomNavigationBarItem(
                            icon: Icons.settings, label: 'Settings')
                      ],
                      onTap: (int index) {
                        setSelectedScreen(index);
                      },
                    ),

```

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật