简体   繁体   中英

TabBarView prevent navigation

I have the following problem:

I have a page with a TapBarView in Flutter. If the customer clicks in the TapBar on another Tap I want to show a Dialog first, like "Do you really want to leave?" with yes / no buttons. If the customer clicks "no" the selected Tap should not change.

Is it possible? If yes... how?

Here is the example:

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
     
    void main() => runApp(MyApp());
     
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
        primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
     
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
     
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return DefaultTabController(
          length: 2,
          child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: [
              Tab(icon: Icon(Icons.android), text: "Tab 1",),
              Tab(icon: Icon(Icons.phone_iphone), text: "Tab 2"),
            ],
          ),
          title: Text('TutorialKart - TabBar & TabBarView'),
        ),
        body: TabBarView(
          children: [
            Center( child: Text("Page 1")),
            Center( child: Text("Page 2")),
          ],
        ),
          ),
        );
      }
    }

Try this. First, in your TabBar you can add any widget, so you can put a button there and inside the onPressed function, you can add the alertDialog for the user:

 TabBar(
            labelColor: Colors.black,
            tabs: [
              ElevatedButton(
                child: Text('First Tab'),
                onPressed: () {
                        //logic for the AlertDialog and inside the AlertDialog you can Navigate to the other tab
                             },
              ),
              Tab(
                text: 'Second Tab',
              ),
            ],
          ),

Let me know if it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM