flutterdartflutter-layoutflutter-webfloating-action-button

Changes icon color by using Floating Action Button


I want to change the Icon color by using a Floating Action Button. If I press red button, the icon changes into red color.

Code :

floatingActionButton: Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        FloatingActionButton.extended(
          icon: Icon(Icons.colorize),
          label: Text('Red'),
          backgroundColor: Colors.red,
        ),

Solution

  • You can do like this (use StatefulWidget widget and setState):

    class ChangeIconColor extends StatefulWidget {
      @override
      ChangeIconColorState createState() => ChangeIconColorState();
    }
    
    class ChangeIconColorState extends State<ChangeIconColor> {
      
      Color selectedColor = Colors.blue;
      
      changeColor(Color color){
        setState(() {
          selectedColor = color;
        });
      }
      
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
            FloatingActionButton.extended(
              onPressed: () {
                changeColor(Colors.red);
              },
              icon: Icon(Icons.colorize),
              label: Text('Red'),
              backgroundColor: Colors.red,
            ),
          ]),
          body: Container(
              child: Icon(
            Icons.lock_clock,
            color: selectedColor,
          )),
        );
      }
    }
    

    if you want to use StatelessWidget you can use ValueNotifier like this:

    class ChangeIconColorState extends StatelessWidget {
      final ValueNotifier<Color> selectedColorNotifier = ValueNotifier(Colors.blue);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
            FloatingActionButton.extended(
              onPressed: () {
                selectedColorNotifier.value = Colors.red;
              },
              icon: Icon(Icons.colorize),
              label: Text('Red'),
              backgroundColor: Colors.red,
            ),
          ]),
          body: Container(
              child: ValueListenableBuilder(
            builder: (context, Color color, child) {
              return Icon(
                Icons.lock_clock,
                color: color,
              );
            },
            valueListenable: selectedColorNotifier,
          )),
        );
      }
    }