Open In App

Flutter – Toggle Buttons

Last Updated : 08 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
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.

Syntax

List Of Bool 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';
 
void main() => runApp(ToggleButtonRun());
 
class ToggleButtonRun extends StatefulWidget {
  @override
  _ToggleButtonRunState createState() => _ToggleButtonRunState();
}
 
class _ToggleButtonRunState extends State<ToggleButtonRun> {
 
  List<bool> _selections = List.generate(3, (_)=>false );
 
  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"),
        ),
        body: Column(
          crossAxisAlignment:CrossAxisAlignment.start,
          children: <Widget>[
            ToggleButtons(
              children: <Widget>[
                Icon(Icons.format_bold),
                Icon(Icons.format_italic),
                Icon(Icons.format_underlined),
              ],
              isSelected:_selections,
              onPressed:(int index){
                setState(() {
                  _selections[index]=!_selections[index];
 
                  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(
              "This Is A Simple Text,Press Buttons Up And See What Gonna Happen",
              style:TextStyle(
                fontWeight:TxtBold,
                fontStyle:TxtItalic,
                decoration:TxtUnder,
              ),
            )
          ],
        )
      ),
    );
  }
}


Output UI: 

Output UI

 

Code Explanation

  • main is a 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 Stateful  Widget As User Is Enabling And Disabling Button And Effect Taken On Text.
  • Creating 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 Widget A Widget Must Be Built.
  • Creating MatrialApp That Allows Us To Set App Title Taking Scaffold As An Home.
  • Scaffold Allow Us to Set AppBar And Body Of The Page.
  • As An AppBar It Simple Title.
  • 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.
  • color Set The Color Of 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 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads