Reputation: 125
If I want to create elevated button in flutter, and make background something like green if condition true, or blue if false
can I use if condition with elevated button?
Upvotes: 1
Views: 880
Reputation: 29
ElevatedButton(
onPressed: () {},
child: Text('button'),
style: ButtonStyle(
backgroundColor:MaterialStateProperty.all( yourCondetion ? Colors.green : Colors.blue,),
),
)
Upvotes: 1
Reputation: 1018
You can create a variable with type ButtonStyle
. We often use a file which includes every button style.
Ex: file button_style.dart
:
var btnStyleGreen = ButtonStyle(color: green)
var btnStyleBlue = ButtonStyle(color: blue)
Your working file:
ButtonStyle yourBtnStyle;
if (isBlue) yourBtnStyle = btnStyleGreen; else yourBtnStyle = btnStyleGreen;
ElevatedButton(
child: Text('Button'),
onPress: () {},
style: yourBtnStyle,
)
That's how a big product often does.
Upvotes: 1
Reputation: 823
Should be like this:
ElevatedButton(
child: Text('My Button')
onPress: () {}
style: ElevatedButton.styleFrom(
primary: isTrue? Colors.green : Colors.blue
)
Upvotes: 1
Reputation: 17900
if you want to use ButtonStyle
:
ElevatedButton(
onPressed: () {},
child: Text('button'),
style: ButtonStyle(
backgroundColor:MaterialStateProperty.all( yourCondetion ? Colors.green : Colors.blue,),
),
),
if you want to use ElevatedButton.styleFrom
:
ElevatedButton(
onPressed: () {},
child: Text('button'),
style: ElevatedButton.styleFrom(
primary: yourCondetion ? Colors.green : Colors.blue,
),
),
Upvotes: 2
Reputation: 1242
Using styleFrom
to style an ElevatedButton:
ElevatedButton(
child: Text('Button'),
onPressed: () {},
style: ElevatedButton.styleFrom({
(condition) ? Colors.green : Colors.red,
}),
),
Upvotes: 1