Sub topic 4
Styling by state with WidgetStateProperty
This chapter assumes you can build a widget tree, use setState, and already know how to set a button's colors with styleFrom. It explains how a button picks its appearance while the user presses, hovers over, focuses, or is blocked from using it.
Why styleFrom is not enough
A button is never in just one condition. At any moment it can be enabled or disabled, hovered by a mouse, focused by keyboard navigation, or pressed by a finger. Flutter calls each of these conditions a state.
styleFrom takes plain values such as one backgroundColor. Internally it turns that value into a rule that Flutter applies to the button's states for you. For example, it dims the color when the button is disabled. That is convenient, but you cannot say "grey when disabled, dark teal when pressed, teal otherwise" with a single color.
To control each state yourself, you build a ButtonStyle by hand. Its properties accept a WidgetStateProperty<T> instead of a plain value.
The model: a function from states to a value
A WidgetStateProperty<T> is an object that answers one question: given the set of states the widget is in right now, what value of type T should be used?
The states are the values of the WidgetState enum. The ones you will use most often are:
| State | Meaning |
|---|---|
| `WidgetState.disabled` | The button has no `onPressed` or `onLongPress` handler. |
| `WidgetState.pressed` | A pointer is currently down on the button. |
| `WidgetState.hovered` | A mouse pointer is over the button. |
| `WidgetState.focused` | The button has keyboard focus. |
| `WidgetState.selected` | The widget is selected, used by toggles and chips. |
| `WidgetState.error` | The widget is in an error condition. |
The widget passes a Set<WidgetState> to your property each time it needs a value. The set can hold several states at once. A button can be hovered and focused at the same time, so you check with contains rather than comparing for equality.
Older Flutter code uses the names MaterialState and MaterialStateProperty. They were renamed to WidgetState and WidgetStateProperty because the idea applies beyond Material widgets. This chapter uses the new names.
Using resolveWith
The most flexible way to build a property is WidgetStateProperty.resolveWith. You pass a function that receives the state set and returns the value.
import 'package:flutter/material.dart';
class ContinueButton extends StatelessWidget {
const ContinueButton({super.key, this.onPressed});
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return FilledButton(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
if (states.contains(WidgetState.disabled)) return Colors.grey;
if (states.contains(WidgetState.pressed)) return Colors.teal.shade700;
return Colors.teal;
}),
),
onPressed: onPressed,
child: const Text('Continue'),
);
}
}The order of the if statements matters. Flutter calls your function and uses the first value you return. Put the most important state first. Here disabled comes before pressed. A disabled button cannot be pressed in practice, but checking it first states the intent and protects you if you later add more states.
The type argument is Color?, not Color. Returning null means "I have no opinion for this state, use the theme's default." That lets you override only the states you care about.
backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
if (states.contains(WidgetState.pressed)) return Colors.teal.shade700;
return null; // fall back to the theme for every other state
}),Shortcuts: all and fromMap
Two helpers cover simpler cases.
WidgetStateProperty.all(value) returns the same value in every state. Use it when a property takes a WidgetStateProperty but you want no variation.
OutlinedButton(
style: ButtonStyle(
side: WidgetStateProperty.all(
const BorderSide(color: Colors.teal, width: 2),
),
),
onPressed: () {},
child: const Text('Details'),
)WidgetStateProperty.fromMap takes a map from states to values. Flutter checks the entries in order and uses the first key that matches the current states. Include a final entry with WidgetState.any as a default.
FilledButton(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.fromMap({
WidgetState.disabled: Colors.grey,
WidgetState.pressed: Colors.teal.shade700,
WidgetState.any: Colors.teal,
}),
),
onPressed: () {},
child: const Text('Continue'),
)fromMap reads well for short lists. Use resolveWith when the logic needs computed values or combined conditions.
Which ButtonStyle properties accept states
Many ButtonStyle properties are state-aware. These are the common ones:
backgroundColorandforegroundColorfor the fill and the text and icon color.overlayColorfor the highlight drawn on hover, focus, and press.elevationandshadowColorfor depth.sidefor the border.padding,minimumSize,shape, andtextStyle.mouseCursorfor the cursor shown over the button.
Some properties, such as tapTargetSize and visualDensity, are not state-aware and take plain values.
This example changes elevation, border, and cursor together:
ElevatedButton(
style: ButtonStyle(
elevation: WidgetStateProperty.resolveWith<double>((states) {
if (states.contains(WidgetState.pressed)) return 0;
if (states.contains(WidgetState.hovered)) return 6;
return 2;
}),
mouseCursor: WidgetStateProperty.resolveWith<MouseCursor>((states) {
return states.contains(WidgetState.disabled)
? SystemMouseCursors.forbidden
: SystemMouseCursors.click;
}),
),
onPressed: () {},
child: const Text('Hover me'),
)Here the type argument is double and MouseCursor, with no ?, because the function always returns a value.
Overlay color is different
overlayColor is drawn on top of the button while the user interacts with it. If you set a solid opaque color, it hides the label. Use a color with partial opacity.
TextButton(
style: ButtonStyle(
overlayColor: WidgetStateProperty.resolveWith<Color?>((states) {
if (states.contains(WidgetState.pressed)) {
return Colors.teal.withValues(alpha: 0.20);
}
if (states.contains(WidgetState.hovered)) {
return Colors.teal.withValues(alpha: 0.08);
}
return null;
}),
),
onPressed: () {},
child: const Text('Learn more'),
)withValues(alpha:) is the current way to set opacity on a Color. Older code uses withOpacity, which is deprecated in recent Flutter releases.
Mixing styleFrom with ButtonStyle
You can combine both approaches. Build a base style with styleFrom, then use copyWith to replace one property with a state-aware version.
final base = FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
);
final style = base.copyWith(
backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
return states.contains(WidgetState.pressed)
? Colors.teal.shade700
: Colors.teal;
}),
);Pass style to the button's style argument. This keeps the layout settings short and puts the state logic in one place.
Common errors
- Disabled button looks enabled. The button only enters the
disabledstate whenonPressedandonLongPressare bothnull. If you pass an empty function such as() {}, the state never appears and your disabled color is never used. - Style has no effect. A
ButtonStyleproperty set on the button overrides the theme, but an explicitnullreturned fromresolveWithfalls back to the theme. If a color never changes, check that an earlierifis not returning first. - Type mismatch.
WidgetStateProperty<Color>andWidgetStateProperty<Color?>are different types.ButtonStyle.backgroundColorexpectsWidgetStateProperty<Color?>?. Specify<Color?>onresolveWith. - State seems wrong on touch screens.
hoveredalmost never occurs on a phone, andfocusedappears only with a keyboard or directional pad. Always give a sensible default in the last line of your function. - Overlay hides the label. An opaque
overlayColorcovers the content. UsewithValues(alpha: ...).
Using WidgetStateProperty in your own widget
WidgetState is not tied to buttons. If you build a custom control, you can track states yourself with a Set<WidgetState> and resolve a property against it. The resolve method does the work.
import 'package:flutter/material.dart';
class StatefulTile extends StatefulWidget {
const StatefulTile({super.key});
@override
State<StatefulTile> createState() => _StatefulTileState();
}
class _StatefulTileState extends State<StatefulTile> {
final Set<WidgetState> _states = {};
final WidgetStateProperty<Color> _color = WidgetStateProperty.fromMap({
WidgetState.pressed: Colors.indigo.shade900,
WidgetState.hovered: Colors.indigo.shade300,
WidgetState.any: Colors.indigo,
});
void _set(WidgetState state, bool on) {
setState(() => on ? _states.add(state) : _states.remove(state));
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => _set(WidgetState.hovered, true),
onExit: (_) => _set(WidgetState.hovered, false),
child: GestureDetector(
onTapDown: (_) => _set(WidgetState.pressed, true),
onTapUp: (_) => _set(WidgetState.pressed, false),
onTapCancel: () => _set(WidgetState.pressed, false),
child: Container(
width: 120,
height: 60,
color: _color.resolve(_states),
),
),
);
}
}The tile adds and removes states as pointer events arrive, then asks the property for the color on every build. Note onTapCancel. Without it, a drag that leaves the tile would leave pressed stuck on.
Summary of the workflow
- Decide which states change the look:
disabled,pressed,hovered,focused. - Pick the
ButtonStyleproperty to vary. - Use
fromMapfor a short list,resolveWithfor logic,allfor a constant. - Return
nullfor states where the theme default is fine. - Check the result on a touch device and on a desktop with a mouse.
Exercise
A FilledButton uses backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) { if (states.contains(WidgetState.pressed)) return Colors.red; if (states.contains(WidgetState.disabled)) return Colors.grey; return Colors.teal; }). The button is passed onPressed: () {} while a form is invalid, but it never turns grey. Why, and how do you fix it?
Show answer
The disabled state only applies when onPressed and onLongPress are null. An empty function keeps the button enabled, so the grey branch never runs. Pass onPressed: _isValid ? _submit : null so the button enters the disabled state when the form is invalid.
Exercise
Write a WidgetStateProperty<Color?> using fromMap that returns amber when hovered, orange when pressed, and teal otherwise. Which entry must come last, and why?
Show answer
WidgetStateProperty.fromMap({WidgetState.pressed: Colors.orange, WidgetState.hovered: Colors.amber, WidgetState.any: Colors.teal}). The WidgetState.any entry must come last because the map is checked in order and any matches every set of states, so an earlier position would hide the other entries. Putting pressed before hovered also means a pressed, hovered button shows orange.