Home > Software engineering >  Change icon color when you press
Change icon color when you press

Time:03-21

I want that my icon color, at start grey, when i press it one time starts being pink, and if pressed again then grey (and all the time like that). I've been looking for posts about it but nothing works. I don't get why my icon color is not changing. Here is my code:

IconButton(
                  icon: Icon(Icons.favorite,
                      size: 30.0,
                      color: (isFavourite == true)
                          ? Colors.red
                          : Color.fromARGB(255, 114, 113, 113)),
                  onPressed: () {
                    setState(() {
                      isFavourite != isFavourite;
                    });
                  })

Thank you!

CodePudding user response:

You're simply using an incorrect statement in your code.

You're using using comparison:

 isFavourite != isFavourite;

so the isFavourite value is not changed.

You need to use:

isFavourite = !isFavourite;

Here is a complete working example using part of your code (you can test it on https://dartpad.dev/):

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Sample",
      home: Scaffold(
        appBar: AppBar(title: const Text("Sample")),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool isFavourite = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: Icon(
            Icons.favorite,
            size: 30,
            color: isFavourite
                ? Colors.red
                : const Color.fromARGB(255, 114, 113, 113),
          ),
          onPressed: () {
            setState(() {
              isFavourite = !isFavourite;
            });
          },
        ),
        const Text("Favourite"),
      ],
    );
  }
}
  • Related