doramcquack
doramcquack

Reputation: 61

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 corresponding to that category.

I tried following the docs, but if I change something in the AppBar it just gives me a reendering error.

Upvotes: 2

Views: 13480

Answers (2)

salihgueler
salihgueler

Reputation: 3622

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),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 5

Sunil
Sunil

Reputation: 3494

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

Upvotes: 0

Related Questions