'Hover Color for Icon
I am trying to implement a favorite Button in Flutter. I am happy with the properties when clicking the button but I am not happy with the hover animation.
I want that only the icon color changes on a hover. I don't like the Bubble around the IconButton. Here is my approach:
MouseRegion FavoriteButton(int index) {
bool _favoriteHover = false;
return MouseRegion(
onHover: (e) {
setState(() {
_favoriteHover = true;
});
},
child: IconButton(
icon: Icon(
_projects[index].favorite
? Icons.favorite
: Icons.favorite_border_outlined,
color: _favoriteHover ? Colors.yellow : Colors.white,
),
onPressed: () {
setState(() {
_projects[index].favorite
? _projects[index].favorite = false
: _projects[index].favorite = true;
// TODO: Save Favorite state to config
});
},
color: Colors.transparent,
),
);
Unfortunately, the icon color does not change on hover. Someone can help?
Solution 1:[1]
You try:
Don't hover: https://i.stack.imgur.com/oxGUh.png
/// Flutter code sample for MouseRegion
// This example makes a [Container] react to being entered by a mouse
// pointer, showing a count of the number of entries and exits.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool _favorite = false;
void _incrementEnter(PointerEvent details) {
setState(() {
_favorite = true;
});
}
void _incrementExit(PointerEvent details) {
setState(() {
_favorite = false;
});
}
Icon setIcon(){
if(_favorite){
return Icon(Icons.favorite);
}
return Icon(Icons.favorite_border_outlined);
}
Color setColor(){
if(_favorite){
return Colors.yellow;
}
return Colors.black;
}
@override
Widget build(BuildContext context) {
return Container(
child: MouseRegion(
onEnter: _incrementEnter,
onExit: _incrementExit,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: setIcon(),
color: setColor(),
onPressed: (){},
),
],
),
),
),
);
}
}
[1]: https://i.stack.imgur.com/UyW2j.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | LihnNguyen |