Flutter tabcontroller index does not respond to changes in the tabbarview
just remove the condition :
if (_controller.indexIsChanging) {
Because every time you start changing from previousIndex to the currentIndex, you rebuild the widget and your _controller.index
is the same as your initial index.
This should work :
_handleTabSelection() {
setState(() {
_currentIndex = _controller.index;
});
}
Doc Says:
indexIsChanging : True while we're animating from [previousIndex] to [index] as a
consequence of calling [animateTo]. This value is true during the [animateTo] animation that's triggered when /// the user taps a [TabBar] tab. It is false when [offset] is changing as a /// consequence of the user dragging (and "flinging") the [TabBarView].
bool get indexIsChanging => _indexIsChangingCount != 0;
int _indexIsChangingCount = 0;
Code:
TabController _controller;
int _selectedIndex = 0;
List<Widget> list = [
Tab(icon: Icon(Icons.card_travel)),
Tab(icon: Icon(Icons.add_shopping_cart)),
];
@override
void initState() {
// TODO: implement initState
super.initState();
// Create TabController for getting the index of current tab
_controller = TabController(length: list.length, vsync: this);
_controller.addListener(() {
setState(() {
_selectedIndex = _controller.index;
});
print("Selected Index: " + _controller.index.toString());
});
}
Sample: https://github.com/jitsm555/Flutter-Problems/tree/master/tab_bar_tricks
Output: