Flutter – Implement SwitchListTile Widget: A Comprehensive Guide

Flutter, Google's UI toolkit, has gained immense popularity for its ease of use and flexibility in building beautiful and natively compiled applications. One commonly used widget in Flutter is SwitchListTile, which provides an elegant way to implement a switch within a ListTile. In this blog post, we'll explore the SwitchListTile widget, its constructor, properties, and walk through a step-by-step implementation with examples.

Overview of SwitchListTile Class

The SwitchListTile class is part of the Flutter material library and inherits from the StatelessWidget class. It is specifically designed to create a ListTile with a switch, making it ideal for scenarios like settings screens or feature toggles.

Constructor of SwitchListTile Class

The constructor for SwitchListTile is as follows:

SwitchListTile({
  Key? key,
  Widget? secondary,
  EdgeInsetsGeometry? contentPadding,
  bool isThreeLine = false,
  bool dense,
  bool selected,
  Widget? title,
  Widget? subtitle,
  bool value,
  ValueChanged<bool>? onChanged,
  Color activeColor,
  Color? tileColor,
  Color? selectedTileColor,
  Color? contentBorderColor,
  MaterialTapTargetSize? materialTapTargetSize,
  FocusNode? focusNode,
  bool autofocus = false,
})

Let's break down some of the key parameters:

  • value: A boolean representing the current state of the switch.
  • onChanged: A callback that is called when the state of the switch changes.
  • title: The primary content of the list tile.
  • subtitle: Additional text displayed below the title.
  • activeColor: The color to use when the switch is on.
  • tileColor: The color to use for the tile's background.
  • contentPadding: The padding around the tile's contents.

Required Tools

Before we dive into the implementation, ensure that you have the following tools set up:

  • Flutter SDK: Install the latest version of Flutter from flutter.dev.
  • Flutter IDE: Use your preferred IDE, such as Visual Studio Code or Android Studio, with the Flutter plugin installed.


Video Demo


Step-by-Step Implementation

Let's create a simple Flutter app to demonstrate the usage of SwitchListTile. We'll implement a feature toggle switch in a settings screen.

Step 1 :Create a new Flutter project:

Open your terminal and run the following commands:

flutter create switch_list_tile_example
cd switch_list_tile_example

Step 2 : Open the lib/main.dart file:

Replace the existing code with the following:

import 'package:flutter/material.dart';


void main() {
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      home: const Scaffold(
        body: MySwitchListTileScreen(),
      ),
    );
  }
}


class MySwitchListTileScreen extends StatefulWidget {
  const MySwitchListTileScreen({super.key});


  @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: const Text('FlutterforGeeks'), // Set the app bar title
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Center(
            child: SwitchListTile(
              title: const Text('Trun On/Off'), // The title of the ListTile
              subtitle: const Text(
                  'Turn this feature on or off'), // Optional subtitle
              secondary:
                  const 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
                });
              },
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Text(
            mess, // Display the message
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
          ),
        ],
      ),
    );
  }
}

In this example, we've created a basic Flutter app with a MySwitchListTile widget, which is a stateful widget containing the SwitchListTile.

Step 3: Run the app:

Execute the following command in your terminal:

flutter run

This will launch the app on an emulator or a connected device.

Step 4: Test the SwitchListTile:

Open the app on your device or emulator, and you should see a screen with an "Enable Feature" SwitchListTile. You can toggle the switch, and the _switchValue will update accordingly.


Video Demo


Conclusion

In this blog post, we explored the SwitchListTile widget in Flutter. We covered its constructor, key properties, and walked through a step-by-step implementation of a feature toggle switch using SwitchListTile. This widget is a powerful tool for creating intuitive and user-friendly interfaces, especially in settings screens or scenarios where switches are commonly used. Flutter's rich set of widgets and flexibility make it an excellent choice for building modern, cross-platform applications.

Description of the image

Related Posts