In this post, we are going to see how to build a simple TabBar in Flutter. We will start with a very basic view to add a tab bar first within an AppBar. We will also see how to add icons and other customizations to a TabBar in a flutter.
Lets get started!
Step 1: Create a project in a flutter in android studio
First Go to your android studio/VS code and create a new flutter app and give the name as flutter_tabs with other default settings.
Step 2: Working with Main.dart
Since you already know that Flutter workes mostly by adding widget and when you run the main dart file the execution of your app starts.
Just give a try to run the app to make sure everything works fine.
To create a TabBar we need to create three things
- Create a TabController.
- Create the tabs.
- Create content for each tab.
Step 3: Add a Stateless Widget to the Main.dart File and give the class name as TabBarDemo
class TabBardemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
Step 3.1 Update the Main() Method to execute the widget
void main() {
runApp(TabBarDemo());
}
Step 4: Adding a TabController
home: DefaultTabController(
length: 3,
child: Scaffold())
Step 4.1: Create a Tab
home: DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: Colors.blueGrey[50],
appBar: AppBar(
title: new Text("Simple Tab Demo"),
backgroundColor: Colors.lightBlue[900],
bottom: TabBar(
tabs: [
Tab(
text: ("One"),
),
Tab(
text: ("Two"),
),
Tab(
text: ("Three"),
)
],
),
),
),
),
Step 4.2: Add a TabView
body: TabBarView(children: [
Center( child: Text("One",style: TextStyle(fontSize: 50),)),
Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
Center( child: Text("Three",style: TextStyle(fontSize: 50),))
]),
Step 5: Run the App (main.dart File)
import 'package:flutter/material.dart';
void main() {
runApp(TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: Colors.blueGrey[50],
appBar: AppBar(
title: new Text("Simple Tab Demo"),
backgroundColor: Colors.lightBlue[900],
bottom: TabBar(
tabs: [
Tab(
text: ("One"),
),
Tab(
text: ("Two"),
),
Tab(text: ("Three"),)
],
),
),
body: TabBarView(children: [
Center( child: Text("One",style: TextStyle(fontSize: 50),)),
Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
Center( child: Text("Three",style: TextStyle(fontSize: 50),))
]),
),
),
);
}
}
class TabBardemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}