Reputation: 3651
New to Flutter and I am using the bottom navigation to switch the page content. Based on debugging, the set state is happening where the correct index number is being captured and assigned to the _selectedPage variable. Yet once I step over that code, the page content remains the same without changing content and the icon 'Home' stays selected in bottom navigation no matter what icon I choose.
Commented parts where I expected a difference when I select a different icon from the nav bar. Please advice.
import 'package:flutter/material.dart';
class LatestFeed extends StatefulWidget{
@override
State<StatefulWidget> createState() => LatestFeedState();
}
class LatestFeedState extends State<LatestFeed>{
@override
Widget build(BuildContext context) {
int _selectedPage = 0;
List pageOptions = [
Text('one1', style: TextStyle(fontSize: 36),), // Expecting a change but now it always remains on this data. No change even when set state changes to different index.
Text('two', style: TextStyle(fontSize: 36),),
Text('three', style: TextStyle(fontSize: 36),),
Text('four', style: TextStyle(fontSize: 36),)
];
return MaterialApp(
home: new Scaffold(
body: pageOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home')
),
BottomNavigationBarItem(
icon: Icon(Icons.rss_feed),
title: Text('feed')
),
BottomNavigationBarItem(
icon: Icon(Icons.featured_play_list),
title: Text('list')
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
title: Text('settings')
),
],
currentIndex: _selectedPage, // expecting different icons to be selected based on this index which is being selected in the set state below. Not seeing any change.
onTap: (int index){
setState(() {
_selectedPage = index; // being assigned correctly yet no effect
});
},
),
),
);
}
}
Upvotes: 0
Views: 596
Reputation: 9593
Place your _selectPage and pageOptions in initState or outside your build method to prevent rebuild whenever setState is called
int _selectedPage;
List<Widget> pageOptions;
@override
void initState() {
super.initState();
_selectedPage = 0;
pageOptions = [
Text('one1', style: TextStyle(fontSize: 36),), // always remains on this data. No change even when set stae changes to different index.
Text('two', style: TextStyle(fontSize: 36),),
Text('three', style: TextStyle(fontSize: 36),),
Text('four', style: TextStyle(fontSize: 36),)
];
}
Whenever you call setState, there will be changes that cause the widgets to rebuild. This means that your build method will be called again. When it gets called, _selectedPage
will be set to 0 again and pageOptions[0] will always be the widget selected.
Upvotes: 1