Given this Flutter code snippet for a BottomNavigationBar, what will be the visible result when the user taps the second item?
BottomNavigationBar( currentIndex: _selectedIndex, onTap: (int index) { setState(() { _selectedIndex = index; }); }, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'), BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'), ], )
Think about what setState does and how currentIndex controls the highlight.
Tapping an item calls onTap, which updates _selectedIndex inside setState. This triggers a rebuild, highlighting the tapped item and allowing the UI to show related content.
In Flutter, why is it important to call setState inside the onTap callback of a BottomNavigationBar?
Think about how Flutter knows to update the screen when data changes.
setState notifies Flutter that the widget's state changed, so it rebuilds the widget tree to show the new selected tab highlight and content.
What is the syntax error in this BottomNavigationBar snippet?
BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: (index) => setState(() => _selectedIndex = index),
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
],
)Check punctuation between parameters.
In Dart, parameters in a widget constructor must be separated by commas. The missing comma after currentIndex causes a syntax error.
Which approach best preserves the state of each tab's content when switching tabs using BottomNavigationBar?
Think about how to keep widgets in memory but only show one at a time.
IndexedStack keeps all children alive but shows only the one at the selected index, preserving their states when switching tabs.
Given this Flutter code, why does tapping BottomNavigationBar items not update the highlighted item?
int _selectedIndex = 0; Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: BottomNavigationBar( currentIndex: _selectedIndex, onTap: (index) { _selectedIndex = index; }, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'), ], ), ); }
Think about how Flutter knows to redraw widgets when state changes.
Without calling setState, Flutter does not know the state changed and does not rebuild the widget, so the highlight does not update.