How to change CupertinoButton background color only when onPressed is called
3,407
Solution 1
You can wrap your CupertinoButton
with a GestureDetector
. Than use the onTapDown
and onTapCancel
to change color only when pressed. Like this:
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Color _buttonColor = Colors.deepPurpleAccent;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: GestureDetector(
onTap: () {
print(_emailValue);
print(_passwordValue);
Navigator.pushReplacementNamed(context, '/products');
},
onTapDown: (tapDetails) {
setState(() => _buttonColor = Colors.black);
},
onTapCancel: () {
setState(() => _buttonColor = Colors.deepPurpleAccent);
},
child: CupertinoButton(
color: _buttonColor,
child: Text('test'),
onPressed: () {},
pressedOpacity: 1.0,
),
),
),
),
);
}
}
Now you can use onTap event on GestureDetector for calling navigation or whatever you need.
Solution 2
If you just want to adjust an opacity of the highlighted button color, you can change pressedOpacity
property:
CupertinoButton(
pressedOpacity: 0.4,
...
The default pressedOpacity
value is 0.1
, which is quite low. I found 0.4
is more natural to native iOS look.
Author by
Amin Memariani
Updated on December 12, 2022Comments
-
Amin Memariani over 1 year
I have tried following code but it does not change the color of the button only when it is pressed.
//class attribute Color bgColor = Colors.deepPurpleAccent; //Widget CupertinoButton( color: bgColor, child: Text('LOGIN', style: TextStyle(fontFamily: 'Roboto',)), borderRadius: const BorderRadius.all(Radius.circular(80.0)), onPressed: () { this.setState(() { bgColor = Colors.black; }); print(_emailValue); print(_passwordValue); Navigator.pushReplacementNamed(context, '/products'); }, ),