How can I make the code below that works in onPressed state work in onHover state?
class _MyState extends State<MyPage> {
bool _flag = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => setState(() => _flag = !_flag), //
child: Text(_flag ? 'Red' : 'Green'),
style: ElevatedButton.styleFrom(
primary: _flag ? Colors.red : Colors.teal,
),
),
),
);
}
}
Note : it didn't work onHover: (isHovering) {setState(() { _flag = !_flag ;});},
CodePudding user response:
onHover
is not a void function. It need to have a value. Try as follows:
Scaffold(
body: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (ctx, i) {
return ButtonItems();
}));
And ButtonItems class
class ButtonItems extends StatefulWidget {
@override
_ButtonItems createState() => _ButtonItems();
}
class _ButtonItems extends State<ButtonItems> {
bool _flag = false;
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onHover: (value) {
setState(() => _flag = !_flag);
},
onPressed: () => setState(() => _flag = !_flag), //
child: Text(_flag ? 'Red' : 'Green'),
style: ElevatedButton.styleFrom(
primary: _flag ? Colors.red : Colors.teal,
),
),
);
}
}