Flutter textbutton hover color

Flutter TextButton Hover Color

In Flutter, you can customize the hover color of a TextButton by defining a custom ButtonStyle with onPressed and onHover properties. Here’s an example:


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextButton(
            onPressed: () {}, // onPressed callback
            style: ButtonStyle(
              foregroundColor: MaterialStateProperty.resolveWith(
                (Set states) {
                  if (states.contains(MaterialState.hovered)) {
                    return Colors.red; // change hover color here
                  }
                  return Colors.blue; // default color
                },
              ),
            ),
            child: Text('Hover Me'),
          ),
        ),
      ),
    );
  }
}
    

In the example above, a TextButton is created with an onPressed callback and a custom button style. The button style’s foregroundColor is defined using the resolveWith method, which allows us to change the color based on the button’s state.

When the button is in the hovered state (i.e., when the user hovers over it), the function within resolveWith returns Colors.red to set the hover color. Otherwise, for other states (default or pressed), it returns Colors.blue as the default color.

You can modify the hover color by changing the return value inside the if statement. Feel free to experiment with different colors to achieve the desired hover effect.

Make sure to wrap this code within a Flutter project to see it in action. Let me know if you have any further questions!

Leave a comment