Sub topic 8
Choosing colors with enough contrast
This chapter assumes you can build layouts with Flutter widgets, know StatelessWidget and StatefulWidget, and can run an app on an emulator or device. You do not need earlier accessibility chapters, but you should know that the semantics tree exists and that automated checks are covered in a later chapter.
Why contrast matters
Contrast is the difference in brightness between a foreground color, such as text, and the background behind it. Low contrast makes content hard to read for people with low vision or color vision deficiency. It also hurts everyone who uses a phone in bright sunlight or on a dim screen.
Contrast is measured as a ratio from 1:1 (no difference, such as white on white) to 21:1 (black on white). The Web Content Accessibility Guidelines (WCAG) define the formula and the thresholds. Flutter has no separate standard, and its test tooling follows WCAG.
The numbers to remember
WCAG level AA is the usual target for apps. Level AAA is stricter and is usually applied only to specific content.
| Content | AA minimum | AAA minimum |
|---|---|---|
| Normal body text | 4.5:1 | 7:1 |
| Large text (18 pt regular or 14 pt bold and above) | 3:1 | 4.5:1 |
| Icons, input borders and other meaningful UI parts | 3:1 | 3:1 (no stricter level) |
| Disabled controls, logos and purely decorative items | No requirement | No requirement |
The "large text" threshold uses points, not Flutter logical pixels, so treat roughly 24 logical pixels regular or 19 bold as the practical boundary. If you are unsure, use the 4.5:1 rule.
How the ratio is computed
The ratio compares the relative luminance of two colors. Relative luminance is a measure of perceived brightness from 0 (black) to 1 (white). The ratio is:
(L1 + 0.05) / (L2 + 0.05)Here L1 is the lighter color's luminance and L2 is the darker one's. Flutter's Color class already exposes computeLuminance(), so you can check a pair yourself.
import 'package:flutter/material.dart';
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() {
const grey = Color(0xFF9E9E9E);
const darkGrey = Color(0xFF616161);
print(contrastRatio(grey, Colors.white).toStringAsFixed(2)); // about 2.68
print(contrastRatio(darkGrey, Colors.white).toStringAsFixed(2)); // about 6.04
}Mid grey on white looks acceptable on a good monitor but fails AA at about 2.7:1. A darker grey passes with room to spare. This is the most common real-world failure: secondary text, hints and placeholders styled in light grey.
What Flutter gives you by default
The Material 3 ColorScheme is designed so that paired roles have enough contrast. Each "on" color is meant to sit on its matching surface:
primarywithonPrimarysecondarywithonSecondarysurfacewithonSurfaceerrorwithonErrorprimaryContainerwithonPrimaryContainer
If you generate a scheme with ColorScheme.fromSeed, the tonal palette keeps these pairs at accessible ratios in the default configuration. Using the pairs together keeps you safe. Mixing them is where failures start, for example placing onPrimary text on a surface background.
import 'package:flutter/material.dart';
ThemeData buildTheme() {
return ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF1565C0)),
);
}
class PairedColors extends StatelessWidget {
const PairedColors({super.key});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Container(
color: scheme.primaryContainer,
padding: const EdgeInsets.all(16),
child: Text(
'Order shipped',
style: TextStyle(color: scheme.onPrimaryContainer),
),
);
}
}Reading colors from the theme, instead of hard-coding hex values in widgets, also means a single fix in the theme corrects every screen.
Common failure points
Default schemes protect you only until you customize. These are the places contrast tends to break.
- Hard-coded greys for secondary text. Replace
Colors.greywithscheme.onSurfaceVariant, which is designed for secondary text. - Text over images. The background changes under the text, so no single color pair is guaranteed. Add a scrim (a semi-transparent dark layer) or place the text on a solid panel.
- Opacity. Wrapping text in
Opacityor usingwithValues(alpha: ...)blends it toward the background and lowers the ratio. Measure the blended result, not the original color. - Brand colors. A bright brand color can work as a background with dark text and fail as text on white. Test both directions.
- Placeholders and borders. Hint text needs 4.5:1. A text field border that identifies the field needs 3:1 against its surroundings.
- State changes. Pressed, selected and focused states can use different colors. Check each one.
Do not rely on color alone
Contrast is only half of the color problem. About 1 in 12 men has some form of color vision deficiency, so red versus green alone fails many people. If color carries meaning, add a second signal.
import 'package:flutter/material.dart';
class FieldError extends StatelessWidget {
const FieldError({super.key, required this.message});
final String message;
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.error;
return Row(
children: [
Icon(Icons.error_outline, color: color),
const SizedBox(width: 8),
Expanded(
child: Text(message, style: TextStyle(color: color)),
),
],
);
}
}The icon and the text carry the error even if the red is not perceived. The same applies to charts (use patterns or direct labels), status dots (add a word) and required fields (add an asterisk or the word "required").
Respecting high-contrast settings
Some users turn on a system high-contrast mode. Flutter reports this through MediaQuery.highContrastOf(context), which is true when the platform has the setting enabled. On platforms that do not report it, the value stays false.
You can supply an alternative theme through MaterialApp:
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const seed = Color(0xFF1565C0);
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: seed),
),
highContrastTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
contrastLevel: 1.0,
),
),
home: const Scaffold(body: Center(child: Text('Hello'))),
);
}
}contrastLevel ranges from -1.0 to 1.0. A value of 1.0 asks the generator for the highest-contrast tonal palette. MaterialApp also has highContrastDarkTheme for dark mode. The contrastLevel parameter exists only in recent Flutter versions, so check that your SDK supports it.
Dark mode is not automatically accessible
A dark theme needs its own check. Pure white text on pure black can cause visual glare for some users, while dim grey on dark grey fails quickly. Generate the dark scheme with brightness: Brightness.dark and test it with the same tools as the light scheme.
final darkScheme = ColorScheme.fromSeed(
seedColor: const Color(0xFF1565C0),
brightness: Brightness.dark,
);Checking contrast in practice
You have three layers of checking, and they catch different things.
- Design time. Use a contrast checker on your palette before writing code. Most design tools and many web-based checkers accept two hex values and report the ratio.
- Code time. A helper like
contrastRatioabove can assert that your theme pairs pass, which guards against someone editing a color later. - Test time. Flutter's
textContrastGuidelinesamples rendered pixels and fails the test when text is too faint. A later chapter covers it in full.
The code-time check works well as a unit test over your theme:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
double contrastRatio(Color a, Color b) {
final la = a.computeLuminance();
final lb = b.computeLuminance();
final hi = la > lb ? la : lb;
final lo = la > lb ? lb : la;
return (hi + 0.05) / (lo + 0.05);
}
void main() {
test('theme text pairs meet AA', () {
for (final brightness in Brightness.values) {
final s = ColorScheme.fromSeed(
seedColor: const Color(0xFF1565C0),
brightness: brightness,
);
expect(contrastRatio(s.onSurface, s.surface), greaterThanOrEqualTo(4.5));
expect(contrastRatio(s.onPrimary, s.primary), greaterThanOrEqualTo(4.5));
expect(contrastRatio(s.onError, s.error), greaterThanOrEqualTo(4.5));
}
});
}A quick decision flow
Summary of habits
- Take colors from
ColorSchemepairs instead of hard-coded values. - Treat light grey text, text over images, and faded text as suspects.
- Check light, dark and high-contrast themes separately.
- Never let color be the only carrier of meaning.
- Add a theme unit test and the
textContrastGuidelinewidget test so regressions fail the build.
Exercise
A designer asks for 16 px regular body text in color #9E9E9E on a white card, and a red dot (with no other marker) to show that a form field is invalid. Which of these two choices fail accessibility guidelines, and how would you fix each one?
Show answer
Both fail. First, #9E9E9E on white is about 2.7:1, below the 4.5:1 needed for normal text at AA. Fix it by using a darker grey such as #616161 (about 6:1) or by reading colorScheme.onSurfaceVariant from the theme. Second, the red dot relies on color alone, so people with color vision deficiency may miss it, and screen reader users get nothing. Fix it by adding an error icon and message text next to the field, and by giving the field an error text through InputDecoration.errorText so the semantics tree also carries the message.
Exercise
You set highContrastTheme on MaterialApp, but when you run the app on a device with high contrast turned off, you still see the normal theme. Is that a bug?
Show answer
No. MaterialApp uses highContrastTheme only when MediaQuery.highContrastOf(context) is true, meaning the platform reports a high-contrast setting. With the setting off, the normal theme is used. Turn on the system setting (or override MediaQueryData.highContrast in a test) to see the alternative theme.