Axen_Rangs
Axen_Rangs

Reputation: 427

Change Icon of toggle button flutter

Is there anyway to change icon of the toggle button on pressed or Is there anyway to make icon button function like toggle button?

I've tried following method but I want to change Icon agian to first one if the button pressed agian.

IconButton( iconSize: 30.0,
            padding: EdgeInsets.only(left:4,right:4,top:0),
            icon: Padding(
            child: pressed ==true ? 
            Icon(Icons.start):Icon(Icons.stop)
                  ),
                  onPressed: () {
                    setState(() {
                      pressed=true;
                    });
                  }

Upvotes: 2

Views: 10035

Answers (2)

alfredo-fredo
alfredo-fredo

Reputation: 652

IconButton(
        iconSize: 30.0,
        padding: EdgeInsets.only(left: 4, right: 4, top: 0),
        icon: Padding(
            padding: EdgeInsets.all(8.0),
            child: pressed == true ? Icon(Icons.start) : Icon(Icons.stop)),
        onPressed: () {
          setState(() {
            pressed = !pressed;
          });
        },
      ),

pressed = !pressed - Is the same as saying pressed is equal to what pressed is currently not. So on press it will switch to true if boolean is false, and false if boolean is true.

Upvotes: 3

I have created a widget using the same code above.

class IconToggleButton extends StatelessWidget {
  final bool isSelected;
  final Function onPressed;
  IconToggleButton({this.isSelected, this.onPressed});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: IconButton(
        iconSize: 30.0,
        padding: EdgeInsets.all(5),
        icon: Padding(
            padding: EdgeInsets.zero,
            child: isSelected == true
                ? Icon(FontAwesome.sort_name_up)
                : Icon(FontAwesome.sort_name_down)),
        onPressed: () {
          onPressed();
        },
      ),
    );
  }
}

Usage:

Create a class variable

 bool isSelected = false;

Use the widget as following:

IconToggleButton(
                        isSelected: isSelected,
                        onPressed: () {
                          setState(
                            () {
                              isSelected = !isSelected;
                            },
                          );
                        },
                      )

Hope that it will help many.

Upvotes: 2

Related Questions