Sub topic 14
Checking contrast and accessibility
This chapter assumes you can already build light and dark themes with ColorScheme.fromSeed, wire theme, darkTheme and themeMode on MaterialApp, and read values with Theme.of(context). It also assumes you have read about ThemeExtension. Here you learn what the Material 3 color system guarantees about contrast, what it does not, and how to check the rest automatically.
What contrast means and which numbers to meet
Contrast ratio compares the relative luminance (perceived brightness) of two colors. It ranges from 1:1 (identical) to 21:1 (black on white). The WCAG 2.x guidelines set these minimums:
| Content | Minimum ratio |
|---|---|
| Body text (under about 18 pt, or 14 pt bold) | 4.5:1 |
| Large text | 3:1 |
| Icons, borders of inputs, focus indicators | 3:1 |
| Disabled controls, pure decoration | No requirement |
Dark themes are not exempt. Light gray text on a dark gray surface can look elegant and still fail 4.5:1.
What the color system gives you for free
ColorScheme.fromSeed builds tonal palettes and assigns each role a fixed tone. Role pairs such as primary/onPrimary, surface/onSurface and primaryContainer/onPrimaryContainer use tones chosen so the pair is readable. In the light scheme primary is around tone 40 and onPrimary is tone 100. In the dark scheme the tones swap to light-on-dark.
The guarantee holds only when you pair the roles as designed. It breaks in these cases:
- You put
onPrimaryonsecondaryContainer, or any other mismatched pair. - You hard-code
Colors.greyorColor(0xFF...)values that were tuned for one brightness. - You apply opacity, such as
onSurface.withValues(alpha: 0.4), to text that must stay readable. - You add custom tokens through
ThemeExtension. Nothing checks those pairs for you. - You draw text over images or gradients.
The ratio is also not a single number per app. Each of the light, dark and high-contrast themes needs its own check.
Measuring contrast in code
Color.computeLuminance() returns the WCAG relative luminance as a value from 0 to 1. The ratio formula is (lighter + 0.05) / (darker + 0.05).
import 'package:flutter/material.dart';
/// WCAG contrast ratio between two opaque colors.
double contrastRatio(Color a, Color b) {
final la = a.computeLuminance();
final lb = b.computeLuminance();
final lighter = la > lb ? la : lb;
final darker = la > lb ? lb : la;
return (lighter + 0.05) / (darker + 0.05);
}This function ignores alpha. For a translucent foreground, composite it over the background first with Color.alphaBlend(foreground, background), then measure the result. Measuring the raw color gives a number that does not match what the user sees.
Testing both themes automatically
A plain unit test can check every pair you rely on, for every brightness. When someone changes the seed color or edits a hard-coded token, the test fails before the change ships.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const seed = Color(0xFF6750A4);
double contrastRatio(Color a, Color b) {
final la = a.computeLuminance();
final lb = b.computeLuminance();
final lighter = la > lb ? la : lb;
final darker = la > lb ? lb : la;
return (lighter + 0.05) / (darker + 0.05);
}
void main() {
for (final brightness in Brightness.values) {
test('role pairs reach 4.5:1 in $brightness', () {
final c = ColorScheme.fromSeed(
seedColor: seed,
brightness: brightness,
);
final pairs = <String, (Color, Color)>{
'primary': (c.primary, c.onPrimary),
'secondary': (c.secondary, c.onSecondary),
'error': (c.error, c.onError),
'surface': (c.surface, c.onSurface),
'surface variant text': (c.surface, c.onSurfaceVariant),
'primaryContainer': (c.primaryContainer, c.onPrimaryContainer),
};
pairs.forEach((name, pair) {
final ratio = contrastRatio(pair.$1, pair.$2);
expect(ratio, greaterThanOrEqualTo(4.5), reason: '$name: $ratio');
});
});
}
}The reason argument puts the pair name and measured ratio in the failure message, so you can see which pair broke without a debugger. Add your own tokens to the map. For example, a BrandColors success pair of Color(0xFF2E7D32) on white measures about 5.1:1, which passes. If you reuse the same success color on a dark surface, add a dark entry. Most colors tuned for light backgrounds fail there.
Checking rendered widgets with guideline matchers
Pair tests check the palette. They cannot tell you whether a real widget puts the right pair together. flutter_test ships guideline matchers that inspect a rendered screen.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
ThemeData buildTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6750A4),
brightness: brightness,
),
);
}
void main() {
for (final brightness in Brightness.values) {
testWidgets('settings screen meets guidelines in $brightness',
(tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(
MaterialApp(
theme: buildTheme(brightness),
home: Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: Center(
child: FilledButton(
onPressed: () {},
child: const Text('Save'),
),
),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
handle.dispose();
});
}
}The three matchers check different things:
textContrastGuidelinerenders the screen and compares text against the pixels behind it.androidTapTargetGuidelinerequires tappable areas of at least 48 by 48 logical pixels. Material'skMinInteractiveDimensionis that same value.labeledTapTargetGuidelinerequires every tappable element to have a semantic label, so screen readers can announce it.
The ensureSemantics handle must stay open while the matchers run, and you must dispose it afterwards.
The contrast matcher depends on what is on screen when it runs. It cannot see states you have not pumped, such as an error message or a pressed button. Write one test per meaningful state.
Offering a high-contrast theme
Some users turn on a system setting such as Increase Contrast. Flutter exposes it as MediaQuery.highContrast, and MaterialApp has two extra parameters that apply when it is true. Platform support differs, and not every platform reports the flag.
ColorScheme.fromSeed also has a contrastLevel parameter. It was added in Flutter 3.22, so check your SDK version. It runs from -1.0 (reduced) through 0.0 (standard) to 1.0 (highest), and it moves tones further apart to raise contrast.
import 'package:flutter/material.dart';
const _seed = Color(0xFF6750A4);
ThemeData _theme(Brightness brightness, {double contrast = 0.0}) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: _seed,
brightness: brightness,
contrastLevel: contrast,
),
);
}
class AccessibleApp extends StatelessWidget {
const AccessibleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: _theme(Brightness.light),
darkTheme: _theme(Brightness.dark),
highContrastTheme: _theme(Brightness.light, contrast: 1.0),
highContrastDarkTheme: _theme(Brightness.dark, contrast: 1.0),
themeMode: ThemeMode.system,
home: const Scaffold(body: Center(child: Text('Accessible theme'))),
);
}
}If you omit the high-contrast themes, MaterialApp falls back to theme and darkTheme. Your test loop should then cover four combinations: light, dark, high-contrast light and high-contrast dark.
Dynamic color and custom tokens
Platform dynamic colors (Material You on Android 12 and later) arrive as complete ColorScheme objects, so the standard role pairs stay readable. Your own ThemeExtension colors do not adapt to the user's wallpaper. A fixed success green can clash with, or lose contrast against, a dynamic surface. The dynamic_color package offers harmonizeWith to nudge a custom color toward the scheme's primary hue. Harmonizing changes the color, so run your contrast test again on the result.
Beyond contrast
- Text scaling. Users can raise the system font size. Test at 2.0 times, because fixed-height containers clip text and
Rowwidgets with long labels overflow. PreferFlexible,Wrapand minimum heights over fixed heights. Do not settextScalerto a fixed value to avoid the problem. - Do not rely on color alone. A red or green status needs an icon or a text label as well. About 8% of men have a color-vision deficiency, and a theme change does not fix that.
- Disabled and placeholder text. Disabled controls are exempt from contrast rules. Hint text in a text field is not, so do not make hints very faint.
- Focus. Keyboard and switch users need a visible focus indicator at 3:1 against its surroundings. Material components provide one, but a custom
InkWellwith a transparentfocusColorremoves it.
Common mistakes
- Testing only the light theme, then discovering in review that dark mode fails.
- Using
withOpacityorwithValues(alpha: ...)on text colors to make secondary text. UseonSurfaceVariantinstead, which was tuned for the purpose. - Measuring a translucent color without compositing it over the background.
- Treating a brand color as a guaranteed readable color. The seed only influences the palette. It is not used directly as
primary. - Assuming the high-contrast theme is used everywhere. It applies only when the platform reports the setting.
Exercise
Your app has a ThemeExtension with warning and onWarning colors. In light mode a test shows 5.3:1, so you reuse the same two colors in dark mode. Why is that risky, and how should you verify the dark version?
Show answer
The extension colors were tuned against a light surface, and fromSeed does not check them. Against dark surfaces the pair may be fine as text on its own background, but any use of warning as a foreground on a dark surface can fall under 3:1 or 4.5:1. Define a separate dark BrandColors instance, then add both pairs (warning against onWarning, and warning against the dark colorScheme.surface if used as an icon or text color) to the per-brightness contrast test with thresholds of 4.5:1 and 3:1 as appropriate.
Exercise
A unit test passes for all role pairs, but a widget test with textContrastGuideline fails on a card that shows text over a photo. Which kind of check caught the problem and why did the unit test miss it?
Show answer
The widget guideline matcher caught it because it compares rendered text against the actual pixels behind it. The unit test only compares palette colors, and a photo background is not a palette color, so the pair test cannot see it. Fix it by adding a scrim (a semi-transparent surface layer) behind the text or by placing the text on a surface-colored panel.