I am developing an app, using the CupertinoApp model. I am using the CupertinoTabView model for the app. Now during development, the tab index resets on hot reload. I tried setting the state on the tab controller but it still resets.
code:
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
CupertinoTabController _controller = CupertinoTabController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
List<Widget> tabs = [
HomeScreen(_controller),
PlaySearchScreen(),
HomeScreen(_controller),
ProfileScreen(),
];
return CupertinoTabScaffold(
controller: _controller,
tabBar: CupertinoTabBar(
items: [
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.play),
label: 'Play Tennis',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.calendar),
label: ' My Schedule',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person),
label: 'Profile',
),
],
),
tabBuilder: (context, index) {
return CupertinoTabView(
builder: (ctx) {
return GestureDetector(
child: tabs[index],
onTap: () => setState(
() => _controller.index = index,
),
);
},
);
});
}
}
class HomeScreen extends StatefulWidget {
HomeScreen(
this.controller, {
Key key,
}) : super(key: key);
final CupertinoTabController controller;
@override
_HomeScreenState createState() => _HomeScreenState();
}
Is there a way to not have it reset?
EDIT
As @p2kr pointed out, you got a mix up in your
build
function (since you also have thedispose
callback inside which you want to define outside thebuild
function) and you make use of theCupertinoTabScaffold
where the documentation states:taken from here. So my original answer applies if you don't make use of the
CupertinoTabScaffold
. In your case, your class should look like this:ORIGINAL
The
CupertinoTabBar
has acurrentIndex
property to maintain a selected tab. Therefore you need to add an additional property to your_HomePageState
:Then in the actual
CupertinoTabBar
we add set thecurrentIndex
property and make use of theonTap
callback to update our property accordingly: