How To Detect With New Tab Is Opened In Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 03-11-2020

I know that when you add a listener to your TabController you can detect when the tab's index is changing by reading the controller's indexIsChanging boolean.

How To Detect With New Tab Is Opened In Flutter Android App

Detect Tabbar Open
 COmplete Code For Detect Tabbar Open In Flutter
 main.dart

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  TabController _tabController;
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    _aListener() {
      setState(() {
        if (_tabController.indexIsChanging) {
          _scaffoldKey.currentState.showSnackBar(SnackBar(
            content: Text("Tabbar Opening"),
          ));
        }
      });
    }

    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: 0,
    )..addListener(_aListener);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: Colors.pink,
        title: Text("Detect Tabbar Open"),
        bottom: TabBar(
          controller: _tabController,
          tabs: <Widget>[
            Tab(
              text: "First Tab",
            ),
            Tab(
              text: "Second Tab",
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: <Widget>[
          Center(
            child: Text("First Tab"),
          ),
          Center(
            child: Text("Second Tab"),
          ),
        ],
      ),
    );
  }
}

Related Post