Flutter make a tab on TabBar navigate to another screen

818 Views Asked by At

I'm trying to develop an app where I have a tabbar in which every tab displays info in the TabBarView. Except the last one ('+ New List), in which I want to show a different screen using Navigator when tapped.

For this purpose I used GestureDetector and on TabBarView I selected an empty Container for that specific tab.

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appState = context.watch<MyAppState>();

    return DefaultTabController(
      length: appState.types.length+2,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Task List'),
          centerTitle: true,
          bottom: 
            TabBar(
              labelColor: Colors.white,
              indicatorColor: Colors.white,
              isScrollable: true,
              labelPadding: EdgeInsets.only(left: 20, right: 20),
              tabs: [
                Tab(icon: Icon(Icons.star_rounded)),
                for (var type in appState.types)
                  Tab(text: type),
                
                GestureDetector(
                  child: Tab(text: '+ New List',),
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(builder: (context) => AddNewList())
                    );
                  },
                )
                
              ]
            ),
        ),
        body: TabBarView(
          children: [
            ShowTaskListPage('favorites'),
            for(var type in appState.types)
              ShowTaskListPage(type),
            Container(),
          ]
        ),
      )
    );
  }
}

The problem is that it works most times as in this screenshot: working, but sometimes when clicking that tab it opens the empty container instead of navigating, as shown in the screenshot: bug

I tried wraping Tab with GestureDetector and the other way around but it still doesn't work

1

There are 1 best solutions below

0
Tiago Fernandes On BEST ANSWER

So after realizing the problem was that I sometimes clicked a bit to the sides and therefore not clicking the GestureDetector but the padding of the Tab, I came up with a different approach. Instead of using GestureDetector I used the onTap property of TabBar.

TabBar(
  labelColor: Colors.white,
  indicatorColor: Colors.white,
  isScrollable: true,
  tabs: [
    Tab(icon: Icon(Icons.star_rounded)),
    for (var type in appState.types)
      Tab(text: type),

    Tab(text: '+ New Label'),
  ],
  onTap: (index) {
    if (index == appState.types.length+1) {
      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => AddNewList())
      );
    }
  },
),