Skip to content Skip to sidebar Skip to footer

Adding Tab Labels To TabView In Flutter

I'm trying to extend the TabView proposed as an answer here. Specifically, instead of the grey dots, I would like to have category labels, and load as a tab content a widget corre

Solution 1:

You can achieve what you wanted via DefaultTabController widget. You can see the example here with only the icons. And here is the modified version of it with titles. TabBar part is for the tab and it's specifications. TabBarView is for the interior view.

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car), text: "Car",),
                Tab(icon: Icon(Icons.directions_transit), text: "Transit"),
                Tab(icon: Icon(Icons.directions_bike), text: "Bike",),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

If you use the code above, you would be getting a 3 tabbed tab view with the explanatory text.

EDIT:

//Call the widget as follows
new TabBarDemo(createTabsDynamically());

//method to use for dynamic creation.
List<Tab> createTabsDynamically() {

    List<String> titles = ["Car", "Transit", "Bike"];
    List<IconData> iconData = [Icons.directions_car, Icons.directions_transit, Icons.directions_bike];
    List<Tab> tabs = new List();
    // Assuming titles and icons have the same length
    for (int i = 0; i< titles.length; i++) {
      tabs.add(Tab(icon: Icon(iconData[i]), text: titles[i],));
    }

    return tabs;
}

class TabBarDemo extends StatelessWidget {

  List<Tab> tabs;
  TabBarDemo(this.tabs);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: tabs,
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

Solution 2:

You can achieve what you wanted via TabController widget. I found a simple example of TabBar here.


Post a Comment for "Adding Tab Labels To TabView In Flutter"