I use the following code to create a PageView
:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
PageController pageController = PageController();
void onTapped(int index) {
setState(() {
_selectedIndex = index;
pageController.animateToPage(index,
duration: const Duration(milliseconds: 300),
curve: Curves.ease);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: PageView(
controller: pageController,
//We can add widets to each tab page
children: [
Container(
color: Colors.red,
),
Container(
color: Colors.blue,
),
Container(
color: Colors.green,
)
],
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.paste), label: 'Report'),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings')
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey,
onTap: onTapped,
),
);
}
}
I can navigate through views by pressing the view icons below but when I use the drag gesture to change the view, the selected view is not changed. How can I fix it?
CodePudding user response:
You can include a listener on PageController
to update the navbar item.
late PageController pageController = PageController()
..addListener(() {
setState(() {
_selectedIndex = pageController.page?.toInt() ?? 0;
});
});
Or onPageChanged
onPageChanged: (value) {
_selectedIndex = value;
setState(() {});
},