Flutter - Implement SwitchListTile Widget
Last Updated :
16 Oct, 2023
The SwitchListTile widget in Flutter is a combination of a ListTile and a switch. It provides a user-friendly way to toggle a boolean setting or option within your app. Here's how you can implement a SwitchListTile widget. A sample video is given below to get an idea about what we are going to do in this article.
Constructor of SwitchListTile Class
SwitchListTile({
Key? key,
required bool value, // The current value of the switch (true for on, false for off).
required ValueChanged<bool?> onChanged, // Callback when the switch is toggled.
Widget? title, // The title of the ListTile.
Widget? subtitle, // Optional subtitle.
Widget? secondary, // Optional leading icon or widget.
bool isThreeLine = false, // Whether the list tile has three lines.
bool dense, // Whether the list tile is dense.
bool controlAffinity = ListTileControlAffinity.platform, // Where to place the control (leading or trailing).
EdgeInsetsGeometry? contentPadding, // Optional padding for the content.
Color? activeColor, // The color to use when the switch is on.
Color? activeTrackColor, // The color to use for the switch's track when it's on.
Color? inactiveThumbColor, // The color to use for the switch's thumb when it's off.
Color? inactiveTrackColor, // The color to use for the switch's track when it's off.
ImageProvider<Object>? activeThumbImage, // The image to display on the thumb when the switch is on.
ImageErrorListener? onActiveThumbImageError, // Callback for errors when loading activeThumbImage.
ImageProvider<Object>? inactiveThumbImage, // The image to display on the thumb when the switch is off.
ImageErrorListener? onInactiveThumbImageError, // Callback for errors when loading inactiveThumbImage.
})
Properties
- title: The primary text displayed in the ListTile.
- subtitle: An optional secondary text displayed below the title.
- secondary: An optional widget (usually an Icon) displayed to the left of the title and subtitle.
- value: The current value of the switch. It's controlled by the _switchValue variable.
- onChanged: A callback function that is invoked when the switch is toggled. It updates the _switchValue variable using setState.
Required Tools
To build this app, you need the following items installed on your machine:
- Visual Studio Code / Android Studio
- Android Emulator / iOS Simulator / Physical Device device.
- Flutter Installed
- Flutter plugin for VS Code / Android Studio.
Step By Step Implementations
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Import the Package
First of all import material.dart file.
import 'package:flutter/material.dart';
Step 3: Execute the main Method
Here the execution of our app starts.
Dart
void main() {
runApp(
MyApp(),
);
}
Step 4: Create MyApp Class
In this class we are going to implement the MaterialApp, here we are also set the Theme of our App.
Dart
// Define the main application widget
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is
// the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListTile', // Set the app's title
theme: ThemeData(
primarySwatch: Colors.green, // Set the app's primary theme color
),
home: MySwitchListTileScreen(), // Set the initial screen to MySwitchListTileScreen
debugShowCheckedModeBanner: false, // Disable the debug banner
);
}
}
Step 5: Create MySwitchListTileScree Class
In this class, we are going to implement a scaffold to display our UI, and Here we are also applying the SwitchListTile widget, The UI contains a SwitchListTile widget and a TextView the TextView will show the state of the SwitchListtTile widget.
Dart
class MySwitchListTileScreen extends StatefulWidget {
@override
_MySwitchListTileScreenState createState() => _MySwitchListTileScreenState();
}
// Define the state for the switch list tile screen
class _MySwitchListTileScreenState extends State<MySwitchListTileScreen> {
bool _switchValue = false; // Initial switch value
String mess = "Truned Off"; // Initial message
// Function to change the message based on the switch value
void changeMessage() {
setState(() {
if (_switchValue) {
mess = "Truned On";
} else {
mess = "Truned Off";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch List Tile Example'), // Set the app bar title
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: SwitchListTile(
title: Text('Trun On/Off'), // The title of the ListTile
subtitle:
Text('Turn this feature on or off'), // Optional subtitle
secondary: Icon(Icons.lightbulb_outline), // Optional leading icon
value: _switchValue, // The current value of the switch
onChanged: (newValue) {
// Callback when the switch is toggled
setState(() {
_switchValue = newValue;
changeMessage(); // Call the function to update the message
});
},
),
),
SizedBox(
height: 20,
),
Text(
mess, // Display the message
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
],
),
);
}
}
Here is the full code to refer to the main.dart file
Dart
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp(),
);
}
// Define the main application widget
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is
// the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListTile', // Set the app's title
theme: ThemeData(
primarySwatch: Colors.green, // Set the app's primary theme color
),
home: MySwitchListTileScreen(), // Set the initial screen to MySwitchListTileScreen
debugShowCheckedModeBanner: false, // Disable the debug banner
);
}
}
// Define the stateful widget for the switch list tile screen
class MySwitchListTileScreen extends StatefulWidget {
@override
_MySwitchListTileScreenState createState() => _MySwitchListTileScreenState();
}
// Define the state for the switch list tile screen
class _MySwitchListTileScreenState extends State<MySwitchListTileScreen> {
bool _switchValue = false; // Initial switch value
String mess = "Truned Off"; // Initial message
// Function to change the message based on the switch value
void changeMessage() {
setState(() {
if (_switchValue) {
mess = "Truned On";
} else {
mess = "Truned Off";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch List Tile Example'), // Set the app bar title
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: SwitchListTile(
title: Text('Trun On/Off'), // The title of the ListTile
subtitle:
Text('Turn this feature on or off'), // Optional subtitle
secondary: Icon(Icons.lightbulb_outline), // Optional leading icon
value: _switchValue, // The current value of the switch
onChanged: (newValue) {
// Callback when the switch is toggled
setState(() {
_switchValue = newValue;
changeMessage(); // Call the function to update the message
});
},
),
),
SizedBox(
height: 20,
),
Text(
mess, // Display the message
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
],
),
);
}
}
Output:
Similar Reads
Flutter - ListTile Widget The ListTile widget is used to populate a ListView in Flutter. It contains a title as well as leading or trailing icons. Let's understand this with the help of an example.Constructor of the ListTile classListTile ListTile({ Key? key, Widget? leading, Widget? title, Widget? subtitle, Widget? trailing
5 min read
Flutter - Implement IndexedStack Widget The IndexedStack widget in Flutter is used to display a single child from a list of children at a given index. It's commonly used when you want to show one child widget while hiding the others, such as in a tabbed interface. In this article, we are going to implement the IndexedStack widget and expl
5 min read
Flutter - RadioListTile Widget RadioListTile is a widget that combines a radio button with a list tile. It is often used in scenarios where you need to present a list of mutually exclusive options, and the user can select one option from the list. Each RadioListTile represents a single option in the list and consists of a title,
5 min read
What is Widgets in Flutter? Flutter is Google's UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a single code base. To build any application we start with widgets - The building block of Flutter applications. Widgets describe what their view should look like given their current configuration and
5 min read
Flutter - Splitting App into Widgets Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and meth
5 min read