To create a TabBar
view in Flutter where each tab displays different content and the tab’s color and text color change when selected, you can follow these steps. We’ll implement three tabs and customize their appearance and behavior.
Step-by-Step Guide to Creating a TabBar View in Flutter
Step 1: Set Up Your Flutter Project
First, make sure you have Flutter installed, and then create a new Flutter project:
bashCopy codeflutter create tabbar_example
cd tabbar_example
Step 2: Update Dependencies (Optional)
For this example, we are using Flutter’s built-in widgets and do not need additional dependencies, so no changes are needed in the pubspec.yaml
.
Step 3: Implement the TabBar in main.dart
Edit the lib/main.dart
file to implement the TabBar
and TabBarView
. Here’s how to set it up:
To display a list of data in the first tab that includes an image and text name in each row, we’ll modify the existing code by adding a ListView
to the first tab’s content. Each item in the ListView
will have an image and text arranged in a Row
widget. We will also include a total count of the list items at the top of the tab.
Here’s how you can modify the main.dart
code to implement this:
Step-by-Step Code Modification to Display a List with Images and Text
1. Add Sample Data
Let’s add some sample data for the list. You can create a simple model for the data items that contain an image URL and a name.
class Item {
final String imageUrl;
final String name;
Item(this.imageUrl, this.name);
}
// Sample data
final List<Item> items = List.generate(
10,
(index) => Item(
'https://via.placeholder.com/150', // Sample image URL
'Item ${index + 1}',
),
);
2. Modify the First Tab to Display a List
Update the _buildTabContent
method to handle the list of items for the first tab. We’ll create a separate widget function to build the list view.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TabBar Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TabBarExample(),
);
}
}
class TabBarExample extends StatefulWidget {
@override
_TabBarExampleState createState() => _TabBarExampleState();
}
class _TabBarExampleState extends State<TabBarExample> with SingleTickerProviderStateMixin {
late TabController _tabController; // Initialize the tab controller
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this); // Set up the TabController with 3 tabs
}
@override
void dispose() {
_tabController.dispose(); // Dispose the controller when the widget is disposed
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TabBar Example'),
bottom: TabBar(
controller: _tabController,
indicatorColor: Colors.black, // Set the bottom border color to black
labelColor: Colors.black, // Set the selected tab text color to black
unselectedLabelColor: Colors.grey, // Set the unselected tab text color to grey
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
onTap: (index) {
setState(() {
_tabController.index = index; // Changes the tab index on tap
});
},
),
),
body: TabBarView(
controller: _tabController,
children: [
_buildListTab(), // Use a separate method to build the list for Tab 1
_buildTabContent('Content for Tab 2', Colors.green),
_buildTabContent('Content for Tab 3', Colors.blue),
],
),
);
}
// Method to build list for Tab 1
Widget _buildListTab() {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Total Items: ${items.length}', // Display the total count of items
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.network(items[index].imageUrl), // Display the image
title: Text(items[index].name), // Display the text
);
},
),
),
],
);
}
// Reuse the _buildTabContent method for Tabs 2 and 3
Widget _buildTabContent(String text, Color color) {
return Container(
color: color,
child: Center(
child: Text(
text,
style: TextStyle(fontSize: 24, color: Colors.white),
),
),
);
}
}
// Sample item data model
class Item {
final String imageUrl;
final String name;
Item(this.imageUrl, this.name);
}
// Sample data for the list
final List<Item> items = List.generate(
10,
(index) => Item(
'https://via.placeholder.com/150', // Placeholder image URL
'Item ${index + 1}',
),
);
Output
Explanation of Key Changes
- Data Model (
Item
):
- Created a simple
Item
class that has animageUrl
andname
to represent each list item.
- Sample Data (
items
List):
- Generated a sample list of
Item
objects with placeholder images and names.
- Custom
Tab 1
Content:
- Used the
_buildListTab
method to create a custom layout for the first tab. This layout includes:- A
Text
widget at the top to display the total number of items. - An
Expanded
widget with aListView.builder
to create a scrollable list of items.
- A
ListTile
is used to display each item in the list with an image (leading
) and a text name (title
).
- Reused
_buildTabContent
for Other Tabs:
- The
_buildTabContent
function is used for the second and third tabs, maintaining the same content as before. TabBar View in flutter
Step-by-Step Guide to Run the App
- Save the Code: Make sure to save the changes to
main.dart
. - Run the App: Use the following command to run the app on a connected device or emulator:
flutter run
What to Expect
When you run the app, the first tab will display a list of 10 items, each with an image and a name. The total count of items will be displayed at the top. Clicking the other tabs will display the content specified for each tab. The selected tab’s text color and the bottom border color will be black, and the unselected tab’s text color will be grey, as per the requirements.
Related Articles
- How to make Ludo app in Flutter with Source Code Step by step
- How to make PDF Reader app in Flutter with Source Code Step by step
- How to make QR Scanner app in Flutter with Source Code Step by step
- How to Make a ToDo App with Flutter with source Code StepWise in 2024
- What is package in Flutter (Dart) with example in 2024
- What is class in Flutter(Dart) with example step by step
- Advantage of Flutter with examples in 2024
- Top 15 Amazing Applications Built with Flutter Framework
- Specialized PDF reader designed specifically for music sheets
- Christmas Quote Generator app built with flutter source code
- How to make review and rating ui with flutter stepwise
- Create custom social login button Google, Facebook and Apple ui