DefaultTabController.of(context).index We can get the current tab index.
If you created a TabController manually, either pass it down to the widget that needs the index or use a GlobalKey:
final _tabController = TabController(length: 3); // Pass to a widget: MyWidget(tabController: _tabController); // Use a GlobalKey: GlobalKey<TabBarState> _tabKey = GlobalKey(); int currentIndex = _tabKey.currentState.index;
Use the currentIndex value to perform actions based on the selected tab:
int currentIndex = _tabController.index;
Use the currentIndex value to perform actions based on the selected tab:
if (currentIndex == 0) { // Perform actions for the first tab } else if (currentIndex == 1) { // Perform actions for the second tab }
Use the addListener method on TabController to get notified when the tab index changes:
_tabController.addListener(() { int currentIndex = _tabController.index; // Perform actions based on the new index });