Adding tab labels to TabView in Flutter

Multi tool use
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.
2 Answers
2
You can achieve what you wanted via TabController widget. I found a simple example of TabBar here.
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.
DefaultTabController
TabBar
TabBarView
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),
],
),
),
),
);
}
}
First you can create your tabs according to your values, then you can pass it with constructor. I edited my code so you can have an idea about it.
– salihguler
Jul 2 at 10:08
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you for the answer. How can i do it dynamically? I have a variable Number of categories so for each category i Need a Tab.
– doramcquack
Jul 2 at 8:46