Flutter
Button style
Customize button color and shape with ButtonStyle.
ButtonStyle and styleFrom
ButtonStyle is the object that customizes a button's appearance. Instead of constructing it directly, it is easier to use the ElevatedButton.styleFrom() helper. The primary parameter of this method sets the button's background color.
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () {},
child: Text('Red'),
)
primary and shape
Inside styleFrom, primary sets the background color and shape sets the corner shape of the button. For example, with RoundedRectangleBorder you can make rounded corners. The style parameter exists on ElevatedButton, TextButton and OutlinedButton alike.
Exercise Make a red ElevatedButton
Write a function select that prints Secildi. In main call select. Add an ElevatedButton; give a red background via style, wire onPressed to select and child to Text('Sec').
Show example solution
import 'package:flutter/material.dart';
void sec() {
print('Secildi');
}
void main() {
sec();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: sec,
child: Text('Sec'),
),
),
),
);
}
}
Test yourself
-
Which method is used to easily create a ButtonStyle?
- ElevatedButton.create()
- ElevatedButton.new()
- ElevatedButton.styleFrom()
- ElevatedButton.build()
Show answer
ElevatedButton.styleFrom() — The ElevatedButton.styleFrom() helper creates a ButtonStyle easily; there is no method named create, new or build.
-
Add the primary parameter
ElevatedButton(
style: ElevatedButton.styleFrom(
____: Colors.red,
),
onPressed: () {},
child: Text('Kirmizi'),
)
Show answer
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () {},
child: Text('Kirmizi'),
)
-
Style parts
- ButtonStyle
- Style object
- styleFrom
- Easy style builder
- primary
- Background color
- shape
- Corner shape of the button
Next lesson: Summary - ElevatedButton