Sub topic 3
Styling buttons with styleFrom and ButtonStyle
This chapter assumes you can build a widget tree with StatelessWidget and StatefulWidget, and that you know Dart closures and the Row, Column and Padding layout widgets. You should also know the four Material button widgets and how onPressed enables or disables them. Here you learn how a button's appearance is resolved, and how to change it at the level that suits the job: one button, one screen, or the whole app.
One style object behind every button
ElevatedButton, FilledButton, OutlinedButton and TextButton all extend ButtonStyleButton. Each one reads its appearance from a ButtonStyle object. A ButtonStyle holds no widgets. It is a bag of optional properties: colors, padding, shape, size, elevation, text style and so on.
Almost every property is a WidgetStateProperty<T?>. This is a function from the set of current interaction states (pressed, hovered, focused, disabled) to a value. The next chapter covers it in detail. For now, remember that a plain color is really "this color in every state".
Writing WidgetStateProperty objects by hand for a simple color change is tedious. That is why each button class has a static styleFrom helper.
styleFrom: the short way
styleFrom takes plain values and returns a ButtonStyle. It is a static method on each button class, and the class decides which defaults it builds on:
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Colors.teal,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
onPressed: () {},
child: const Text('Save'),
)The commonly used parameters are:
| `styleFrom` parameter | What it controls |
|---|---|
| `foregroundColor` | Text and icon color |
| `backgroundColor` | Fill color |
| `disabledForegroundColor`, `disabledBackgroundColor` | Colors when `onPressed` is null |
| `overlayColor` | Base color for hover, focus and pressed highlights |
| `elevation`, `shadowColor` | Shadow depth and color |
| `padding` | Space between the button edge and its child |
| `minimumSize`, `maximumSize`, `fixedSize` | Size constraints |
| `side` | Border color and width (`BorderSide`) |
| `shape` | Outline, such as `StadiumBorder` or `RoundedRectangleBorder` |
| `textStyle` | Font size, weight and so on |
| `iconColor` | Color of an icon given with the `.icon` constructors |
| `tapTargetSize`, `visualDensity` | Hit area and compactness |
Older code uses primary and onPrimary. These were replaced by backgroundColor and foregroundColor. In new code, treat the old names as deprecated.
A null argument means "don't touch this"
Every styleFrom argument defaults to null. A null does not mean "no color". It means "this property is not set here, so use the next source down". That is what lets you override only one thing, such as the background, and keep all the other defaults.
Where the final value comes from
Flutter resolves each property separately. For every property, the first source that supplies a non-null value wins.
This resolution runs property by property, not style by style. If the widget's style sets only backgroundColor, the shape and padding still come from the theme. This is the main reason to prefer a theme for app-wide looks.
Theming all buttons at once
Put a shared style in ThemeData. Each button family has its own theme: elevatedButtonTheme, filledButtonTheme, outlinedButtonTheme and textButtonTheme. The values are ...ButtonThemeData objects that hold a ButtonStyle.
This complete app sets a shared shape and padding in the theme, then overrides only the color on one button and the disabled look on another:
import 'package:flutter/material.dart';
void main() => runApp(const StyleDemo());
class StyleDemo extends StatelessWidget {
const StyleDemo({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FilledButton(
onPressed: () {},
child: const Text('Themed'),
),
const SizedBox(height: 16),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Colors.deepOrange,
),
onPressed: () {},
child: const Text('Color overridden'),
),
const SizedBox(height: 16),
FilledButton(
style: FilledButton.styleFrom(
disabledBackgroundColor: Colors.grey.shade300,
disabledForegroundColor: Colors.grey.shade600,
),
onPressed: null,
child: const Text('Disabled'),
),
],
),
),
),
);
}
}The second button keeps the rounded shape and padding from the theme. Only its background changes.
Building ButtonStyle directly
styleFrom covers most needs. Use ButtonStyle directly when you need a property to depend on state, or when you need a property that styleFrom does not expose. The constructor takes WidgetStateProperty values, so a constant needs a wrapper:
FilledButton(
style: const ButtonStyle(
minimumSize: WidgetStatePropertyAll<Size>(Size(160, 48)),
elevation: WidgetStatePropertyAll<double>(4),
),
onPressed: () {},
child: const Text('Wide'),
)WidgetStatePropertyAll(value) means "this value in every state". It is the same thing as WidgetStateProperty.all(value).
Combining styles with copyWith and merge
A ButtonStyle is immutable, but you can derive new ones from it:
copyWithreturns a copy with the named properties replaced. A replaced property replaces the wholeWidgetStateProperty.merge(other)fills in this style's null properties fromother. Non-null properties on this style win.
A common pattern is to start from styleFrom and add what it cannot express:
final ButtonStyle base = FilledButton.styleFrom(
backgroundColor: Colors.teal,
foregroundColor: Colors.white,
);
final ButtonStyle wide = base.copyWith(
minimumSize: const WidgetStatePropertyAll<Size>(Size(200, 48)),
);You can then pass wide to as many buttons as you like. Keeping shared styles in a const or final variable avoids repeating the same arguments across a screen.
Sizing and the tap target
Material 3 buttons have a default minimum size of 64 by 40 logical pixels. They also pad their hit area out to 48 by 48 when tapTargetSize is MaterialTapTargetSize.padded, which is the default on touch platforms. This is deliberate. It keeps small buttons easy to press.
Two properties change this and they are easy to confuse:
minimumSizechanges how large the visible button must be.Size.zerolets it shrink to fit its content.tapTargetSizechanges how much invisible space is added for touch.MaterialTapTargetSize.shrinkWrapremoves it.
Setting both to compact values produces buttons that look tidy but are hard to hit. If you do that, check the result against the touch target guidance in the accessibility chapter.
Common errors
The color change does nothing. Several things cause this. You may have set backgroundColor on a TextButton, which has a transparent default, but also passed a foregroundColor that matches it, so the text vanishes. Or you may have styled a button that is disabled. A disabled button ignores backgroundColor and uses disabledBackgroundColor, so set both when you care about both states.
The text color is right but the icon is not. With the .icon constructors, the icon uses iconColor when it is set, and otherwise follows foregroundColor. If you set iconColor once in a theme, a later foregroundColor on one button does not recolor the icon.
The border disappears or the shape looks wrong on an OutlinedButton. The border is controlled by side, and the outline by shape. If you pass a new shape and no side, the theme's side is still used. If you pass shape with its own side inside, such as RoundedRectangleBorder(side: ...), behavior can differ between widget and theme sources. Set side explicitly to get predictable results.
A const error with styleFrom. styleFrom is a method call, so it cannot be used inside a const expression. Write style: FilledButton.styleFrom(...) on a non-const button. If you want a compile-time constant style, build a const ButtonStyle(...) with WidgetStatePropertyAll values instead.
Styling the wrong family. ElevatedButton.styleFrom returns a style tuned for elevated buttons. Passing it to a FilledButton compiles, because both take a ButtonStyle. But the null properties are filled in with different defaults, so the result can look off. Use the styleFrom that matches the widget.
Choosing a level
| Situation | Use |
|---|---|
| One button looks different | `styleFrom` on that button |
| A group of buttons shares a look | A shared `ButtonStyle` variable |
| Every button of a kind should match | The matching `...ButtonTheme` in `ThemeData` |
| Appearance depends on pressed, hovered or disabled | `ButtonStyle` with `WidgetStateProperty` (next chapter) |
Prefer the theme for anything the whole app should share. Per-widget styles that repeat the same values are hard to change later.
Exercise
A FilledButton sits in an app whose filledButtonTheme sets rounded corners and 24 pixel horizontal padding. You give that one button style: FilledButton.styleFrom(backgroundColor: Colors.red). What shape and padding does the button have, and why?
Show answer
It keeps the rounded corners and the 24 pixel padding from the theme. Flutter resolves each style property separately, and styleFrom leaves every argument you did not pass as null. A null property falls through to the theme, so only the background color comes from the widget's own style.
Exercise
Write a ButtonStyle variable named compact for a TextButton that removes the extra invisible tap padding and lets the button shrink to its content. Which two properties do you set?
Show answer
Set minimumSize to Size.zero and tapTargetSize to MaterialTapTargetSize.shrinkWrap. For example: final compact = TextButton.styleFrom(minimumSize: Size.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap);. minimumSize controls the visible size, and tapTargetSize controls the added touch area.