'How to change screen index after sliding the tab? flutter

i am using tabbar view with my app that have same floating action button:

  floatingActionButton: FloatingActionButton(
      onPressed: () async{
        print("this is the current Screen :$currentScreen");
        if(currentScreen==0)
        {
          await showInformationDialog(context);
        }
        else
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddNewVehical(1),
            ),
          );
      },

but when i tap on tab it works perfectly and the currentscreen variable changes from 0 to 1 as expected but problem arises when i slide from one tab to another the currentscreen variable print always zero due to which on the other tab it also shows dialogue

can anyone tell me why this is happening? and a solution for it ? Thanks in advance <3



Solution 1:[1]

You can add TabController listener in initState().

 _tabController!.addListener(_handleTabSelection);

In _handleTabSelection method, get the tabController index.

  currentScreen = _tabController!.index; 

Solution 2:[2]

You can use TabController. With the index property you can get the currentIndex. reference : https://api.flutter.dev/flutter/material/TabController-class.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Joe
Solution 2 Ikaras