Open In App

Flutter - Toggle Buttons

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A toggle button allows the user to change a setting between two states. You can add a basic toggle button to your layout with the ToggleButton object. A sample video is given below to get an idea about what we are going to do in this article.

Demo Video:

Syntax

List Of Booleans to Know Which Selected:

3 Represent Number Of Items, 3 Items Set To Not Selected(False).

Dart
List<bool>_selections = List.generate(3, () =>false);


Widget:

Dart
ToggleButtons(

children: <Widget>[

    Icon(Icons.format_bold), Icon(Icons.format_italic), Icon(Icons.format_underline),
        isSelected:_selections, on Pressed:(int index){
            setState(() {
                        _selections[index]=!_selections[index];
                if(index==0 && _selections[index]){
                    // Do something
                } else if(index==0 && !_selections[index]){ 
                      // Do something
            }
            // You Can Compare Other Indexes Too
    });
},

    color:Colors.teal, 
    fillColor:Colors.deep Purple,
  
)


Code Example 

Dart
import 'package:flutter/material.dart';

// Entry point of the application
void main() => runApp(ToggleButtonRun());

// Stateful widget to manage the state of the toggle buttons
class ToggleButtonRun extends StatefulWidget {
  @override
  _ToggleButtonRunState createState() => _ToggleButtonRunState();
}

class _ToggleButtonRunState extends State<ToggleButtonRun> {
  // List to track the selection state of the toggle buttons
  List<bool> _selections = List.generate(3, (_) => false);

  // Variables to store the text style properties
  var TxtBold = FontWeight.normal;
  var TxtItalic = FontStyle.normal;
  var TxtUnder = TextDecoration.none;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, 
      title: 'Toggle Buttons', 
      home: Scaffold(
        appBar: AppBar(
          title: Text("Toggle Buttons"), 
          backgroundColor: Colors.teal, 
          foregroundColor: Colors.white, 
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0), 
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, 
            children: <Widget>[
              // ToggleButtons widget to toggle text styles
              ToggleButtons(
                children: <Widget>[
                  Icon(Icons.format_bold), // Bold icon
                  Icon(Icons.format_italic), // Italic icon
                  Icon(Icons.format_underlined), // Underline icon
                ],
                isSelected: _selections, // Track the selection state
                onPressed: (int index) {
                  setState(() {
                    // Toggle the selection state
                    _selections[index] = !_selections[index];

                    // Update text style based on the selected button
                    if (index == 0 && _selections[index]) {
                      TxtBold = FontWeight.bold;
                    } else if (index == 0 && !_selections[index]) {
                      TxtBold = FontWeight.normal;
                    }

                    if (index == 1 && _selections[index]) {
                      TxtItalic = FontStyle.italic;
                    } else if (index == 1 && !_selections[index]) {
                      TxtItalic = FontStyle.normal;
                    }

                    if (index == 2 && _selections[index]) {
                      TxtUnder = TextDecoration.underline;
                    } else if (index == 2 && !_selections[index]) {
                      TxtUnder = TextDecoration.none;
                    }
                  });
                },
                color: Colors.teal, 
                fillColor: Colors.deepPurple, 
              ),
              // Text widget to display the styled text
              Text(
                "This Is A Simple Text,Press Buttons Up And See What Gonna Happen",
                style: TextStyle(
                  fontWeight: TxtBold, // Apply bold style
                  fontStyle: TxtItalic, // Apply italic style
                  decoration: TxtUnder, // Apply underline style
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}


Output UI: 

Toggle_Button


Code Explanation

  • main is the principal method called once the program is loaded.
  • Once the Program Is Loaded, runApp Will Run And Call The Class That We Created(ToggleButtonRun) To Be Run.
  • This Class Is a Stateful  Widget As the User Is Enabling And Disabling the Button And the Effect Taken On the Text.
  • Creating a State Class ToggleButtonRunState That Extends Its Main State From Class ToggleButtonRun.
  • Creating List Variable selections, taking 3 bool Variable Set To False (Bold -> false, Italic->false, Underline -> false).
  • Creating Variable TxtBold Used To Set Text Between Bold If Button Toggled And Normal If Not.
  • Creating Variable TxtItalic Used To Set Text Between Italic If Button Toggled And Normal If Not.
  • Creating Variable TxtUnder Used To Set Text Underlined If Button Toggled And None If Not.
  • As Flutter Is Based On widgets, A Widget Must Be Built.
  • Creating a MaterialApp That Allows Us To Set the App Title, Taking the Scaffold As a Home.
  • Scaffold Allow Us to Set the AppBar And Body Of The Page.
  • As An AppBar, It is a Simple Title With Background Color And Foreground Color.
  • As An Body, It Takes Column Layout (Elements Represented Each On-Line).
  • First Row Take ToggleButtons That Take Items As Children (Icons), isSelected Take A List Of bool Created Up That Initialize All Buttons To False (Not Selected) When Each Pressed We Switch It From False to True Set By (Inverse) And Checking Index And If Selected Then Putting Effect If Not Removing Effect To Normal.
  • Set The Color Of The ToggleButton Icon When Selected, fillColor Set BackgroundColor Of The Toggle Button When Selected.
  • Second Row Take Text Where Style Taken By Variables That Switch When Button Is Toggled (Bold To Normal Par Example..).

Output 

the


Next Article
Article Tags :

Similar Reads