Change Material button color onPress and back to default onLongPress
208
//declare color variable
Color myColor=Colors.white;
//set myColor to material button
color:myColor;
//in setstate use it like this
setState({
myColor=Colors.white; or myColor=Colors.orange;
})
Author by
Jon
Updated on December 19, 2022Comments
-
Jon over 1 year
Hi I am still new to flutter but was trying to make a pretty simple app I thought.
This app consists of 30 buttons each in their own container. Code to follow. All I am trying to do is if a button is pressed then it will turn orange and then if it is longPressed that it goes back to its default color of white. Can someone explain how to do this. Here is an example of just 1 button.
Container( width: 65, height: 65, child: MaterialButton( shape: CircleBorder( side: BorderSide( width: 5, color: Colors.blue[900], style: BorderStyle.solid)), child: Text( "1", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), color: Colors.white, textColor: Colors.black, onPressed: () { setState(() { color: Colors.orange; }); }, onLongPress: (){ setState(() { color: Colors.white; }); }, ), ),
Thanks in Advance
-
Jon about 3 yearsty for your reply but when i try that it says that color is undefined
-
Biruk Telelew about 3 yearsdeclare Color myColor=Colors.white and set color:myColor instead of color:Colors.white and use the code in my answer
-
Jon about 3 yearstyvm that worked... it kind of sucked that i had to create a seperate var for each button but thats cuz i know very little still and assume there is an easier way...For now although clunky it works so I am very happy tyvm
-
Jon about 3 yearsty for your feedback.. It works great as also suggested above. Although this is a solution like above I selected the First answer as the correct one only because he answered first but tyvm anyways.