How can I hover my TextButtons in Flutter?

I created three textbuttons in Flutter and now I want to hover their color from their default color to pink color. In the moment that my mouse is on the button, the button should change it’s color to pink. Can anyone tell me how to fix this?

Container(
          color: Colors.grey[900],
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {},
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.grey[600])),
                child: const Text(
                  'Registrieren',
                  style: TextStyle(color: Colors.white,fontSize: 20,),
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              TextButton(
                onPressed: () {},
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.grey[600])),
                child: const Text(
                  'Login',
                  style: TextStyle(color: Colors.white,fontSize: 20,),
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              TextButton(
                onPressed: () {},
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.grey[600])),
                child: const Text(
                  'Kontakt',
                  style: TextStyle(color: Colors.white,fontSize: 20,),
                ),
              )
            ],
          ),
        ),

>Solution :

To set hover over color:

  1. Inside the Style property, add the ButtonStyle().
  2. Now, inside the ButtonStyle() add the foregroundColor or backgroundColor and decide which color to show based on the MaterialState.

Code Example:

TextButton(
  onPressed: () {},
  style: ButtonStyle(
    foregroundColor: MaterialStateProperty.resolveWith<Color>(
        (Set<MaterialState> states) {
      if (states.contains(MaterialState.hovered))
        return Colors.green;
      return Colors
          .purpleAccent;
    }),
  ),
  child: const Text(
    'Text Button ',
    style: TextStyle(fontSize: 24),
  ),
)

Leave a Reply