I am new to flutter, and I want to reduce code duplication when it comes to UI.
Let's say that I chose some theme. ElevatedButton
will have color of that theme.
Now, I want to have some buttons that will by styled alternatively (e.g. 'Cancel' buttons to be grey or 'Accept' buttons to be bright green).
Normally I do like this:
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.grey[100]),
onPressed: () {
// onPressed logic here
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.black54),
),
),
but if I have multiple Cancel buttons, this code would be repeated:
style: ElevatedButton.styleFrom(primary: Colors.grey[100]),
and
style: TextStyle(color: Colors.black54),
What is "Flutter" way to achieve it so I can have "Cancel" or "Accepted" style defined in one place? Should I create my own widget CancelButton
? or is there better way?
ElevatedButton(
style: Styles.cancelButtonStyle(),
onPressed: () {
// onPressed logic here
},
child: const Text(
'Cancel',
style: Styles.cancelButtonTextStyle(),
),
),
Your Custom Style Class
class Styles{
static TextStyle cancelButtonTextStyle(){
return TextStyle(
fontSize: 16,
color: Colors.black54
);
}
static TextStyle acceptButtonTextStyle(){
return TextStyle(
fontSize: 16,
color: Colors.black54
);
}
static ButtonStyle cancelButtonStyle(){
return ElevatedButton.styleFrom(primary: Colors.grey[100]);
}
static ButtonStyle acceptButtonStyle(){
return ElevatedButton.styleFrom(primary: Colors.green[700]);
}
}