In flutter implementing a tab layout is easy and straightforward. This is a simple example from the official documentation:
import 'package:flutter/material.dart'; void main() { runApp(new TabBarDemo()); } class TabBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new DefaultTabController( length: 3, child: new Scaffold( appBar: new AppBar( bottom: new TabBar( tabs: [ new Tab(icon: new Icon(Icons.directions_car)), new Tab(icon: new Icon(Icons.directions_transit)), new Tab(icon: new Icon(Icons.directions_bike)), ], ), title: new Text('Tabs Demo'), ), body: new TabBarView( children: [ new Icon(Icons.directions_car), new Icon(Icons.directions_transit), new Icon(Icons.directions_bike), ], ), ), ), ); } }
But here is the thing, I want to get the active tab index so I can apply some logic on certain tabs. I search the documentation but I wasn't able to figure it out. Can you guys help and thanks?
Setting up TabBar in Flutter Here's the minimal code to get TabBar up and running: DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( bottom: TabBar( tabs: [ Tab(icon: Icon(Icons. flight)), Tab(icon: Icon(Icons.
To create a tab in it, create a tab list and create an object of its TabController. TabController _tabController; Initalize the TabController inside the initState() method and also override it in the dispose() method.
DefaultTabController is an inherited widget that is used to share a TabController with a TabBar or a TabBarView. It's used when sharing an explicitly created TabController isn't convenient because the tab bar widgets are created by a stateless parent widget or by different parent widgets.
The whole point of DefaultTabController
is for it to manage tabs by itself.
If you want some custom tab management, use TabController
instead. With TabController
you have access to much more informations, including the current index.
class MyTabbedPage extends StatefulWidget { const MyTabbedPage({Key key}) : super(key: key); @override _MyTabbedPageState createState() => new _MyTabbedPageState(); } class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin { final List<Tab> myTabs = <Tab>[ new Tab(text: 'LEFT'), new Tab(text: 'RIGHT'), ]; TabController _tabController; @override void initState() { super.initState(); _tabController = new TabController(vsync: this, length: myTabs.length); } @override void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( bottom: new TabBar( controller: _tabController, tabs: myTabs, ), ), body: new TabBarView( controller: _tabController, children: myTabs.map((Tab tab) { return new Center(child: new Text(tab.text)); }).toList(), ), ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With