Home > Software engineering >  How to change Flutter ElevatedButton style with if condition?
How to change Flutter ElevatedButton style with if condition?

Time:10-12

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?

CodePudding user response:

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,
  ),
),

CodePudding user response:

Using styleFrom to style an ElevatedButton:

      ElevatedButton(
        child: Text('Button'),
        onPressed: () {},
        style: ElevatedButton.styleFrom({
          (condition) ? Colors.green : Colors.red,
        }),
      ),

CodePudding user response:

Should be like this:

ElevatedButton(
  child: Text('My Button')
  onPress: () {}
  style: ElevatedButton.styleFrom(
    primary:  isTrue? Colors.green : Colors.blue
)

CodePudding user response:

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.

CodePudding user response:

ElevatedButton( onPressed: () {}, child: Text('button'), style: ButtonStyle( backgroundColor:MaterialStateProperty.all( yourCondetion ? Colors.green : Colors.blue,), ), )

  • Related