I am using DefaultTabController and BottomNavigationBar to show my tabs. When I want to go to homepage from a different page. For e.g, from SubmitForm() page, I will call navigation back to a specific tab index. In this case, I want to go to SearchFacilities() so the index will be 1. I will do Get.to(() => HomePage(selectedPage: 1). However, it still leads me to index: 0 (Locations()) page, and not index: 1 (SearchFacilities()) page.
class HomePage extends StatefulWidget {
const HomePage({
Key? key,
required this.selectedPage,
}) : super(key: key);
final int selectedPage;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final screens = [
Locations(),
SearchFacilities(),
SearchCommodities(),
Settings(),
];
int _currentIndex = 0;
void _updateIndex(int value) {
setState(() {
_currentIndex = value;
});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
initialIndex: widget.selectedPage,
child: Scaffold(
body: screens[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
// backgroundColor: Colors.white,
// fixedColor: Colors.black,
// type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
onTap: _updateIndex,
items: [
BottomNavigationBarItem(
label: "Locations",
icon: _currentIndex == 0
? SvgPicture.asset(
'assets/building.svg',
width: screenWidth(context) / 8,
)
: SvgPicture.asset(
'assets/buildinggrey.svg',
width: screenWidth(context) / 8,
)),
BottomNavigationBarItem(
label: "Facilities",
icon: _currentIndex == 1
? SvgPicture.asset(
'assets/repair.svg',
width: screenWidth(context) / 8,
)
: SvgPicture.asset(
'assets/repairgrey.svg',
width: screenWidth(context) / 8,
)),
BottomNavigationBarItem(
label: "Commodities",
icon: _currentIndex == 2
? SvgPicture.asset(
'assets/commodities.svg',
width: screenWidth(context) / 8,
)
: SvgPicture.asset(
'assets/commoditiesgrey.svg',
width: screenWidth(context) / 8,
)),
BottomNavigationBarItem(
label: "Settings",
icon: _currentIndex == 3
? SvgPicture.asset(
'assets/settingsgrey.svg',
width: screenWidth(context) / 8,
)
: SvgPicture.asset(
'assets/settingsgrey.svg',
width: screenWidth(context) / 8,
)),
],
),
),
);
}
}
You've taken the parameter selectedPage
in HomePage
as :
HomePage(selectedPage: 1)
But, you're not doing anything with that selectedPage
.
Change your _HomePageState
as follows :
class _HomePageState extends State<HomePage> {
final screens = [
Locations(),
SearchFacilities(),
SearchCommodities(),
Settings(),
];
int _currentIndex = 0;
void _updateIndex(int value) {
setState(() {
_currentIndex = value;
});
}
@override
void initState() {
super.initState();
_currentIndex = widget.selectedPage;
}
@override
Widget build(BuildContext context) {...}
}