2

I have a TabBarView(), and i need to show a MessageDialog (showDialog) asking if really want to leave this tab. is there any way to do it?

this is the body of my code

child: Scaffold(
        drawer: SideMenu(),
        appBar: AppBar(
          title: Text("Antecedentes"),
          bottom: TabBar(
            isScrollable: true,
            controller: _controller,
            tabs: [
              Tab(text: 'Tab # 1'),
              Tab(text: 'Tab # 2'),
              Tab(text: 'Tab # 3'),

          ),
        ),
        body: TabBarView(
          controller: _controller,
          children: [
            TabOnePage(),
            TabTwoPage(),
            TabThreePage(),

          ],
        ),
      ),

Im using version 2.2.3 of Flutter. I appreciate help on this .

  • check this out and let me know if it works https://stackoverflow.com/questions/55485466/how-to-detect-tabbar-change-in-flutter – Sagar Acharya Sep 14 '21 at 06:56

1 Answers1

1

Show AlertDialog on Tabbar onTap action, and set TabBar index to previous one(this will allow TabBar to stay on the same tab):

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Tabbar Demo"),
          bottom: TabBar(
            onTap: (index) {
              print(index);
              showAlert(tabController.index);
              tabController.index = tabController.previousIndex;
            },
            unselectedLabelColor: Colors.white,
            labelColor: Colors.black,
            tabs: [
              Tab(icon: Icon(Icons.chat)),
              Tab(icon: Icon(Icons.drafts)),
              Tab(icon: Icon(Icons.ac_unit))
            ],
            controller: tabController,
            indicatorColor: Colors.black,
            indicatorSize: TabBarIndicatorSize.tab,
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            CustomView("First"),
            CustomView("Second"),
            CustomView("Third"),
          ],
          controller: tabController,
        ));
  }

And upon selection of the "OK" button in the AlertDialog, set Tabbar index to the new one.

  void showAlert(int newIndex) {
    AlertDialog alertDialog = new AlertDialog(
      content: new Container(
        height: 80.0,
        child: new Column(
          children: <Widget>[
            new Text("Want to leave this tab?"),
            new RaisedButton(
              child: new Text("OK"),
              onPressed: () {
                tabController.index = newIndex;
                Navigator.pop(context);
              },
            )
          ],
        ),
      ),
    );
    showDialog(context: context, child: alertDialog);
  }
RTXGamer
  • 3,215
  • 6
  • 20
  • 29