Sub topic 14
Showing icons with the Icon widget
This chapter assumes you can write a StatelessWidget, read named parameters in Dart, and run a Flutter app with MaterialApp. It also assumes pubspec.yaml is familiar to you. The Icon widget draws a small glyph, such as a heart, a magnifying glass, or a home symbol. You will see how Icon works internally, which parameters it accepts, and which mistakes cause missing or oversized icons.
What an Icon actually is
An Icon is not an image file. It draws one character from an icon font. The font that ships with Flutter's Material library is called MaterialIcons. The Icons class holds hundreds of constants such as Icons.home and Icons.search. Each constant is an IconData, which stores a code point (a number that picks a glyph) and the name of the font family that contains it.
Because the glyph is text, it is a vector. It stays sharp at any size and can be recolored with a single color value. You do not need to supply 1x, 2x, and 3x versions as you do for bitmaps.
A first example
The program below is complete. It shows one icon at its defaults and one with explicit styling.
import 'package:flutter/material.dart';
void main() => runApp(const IconDemo());
class IconDemo extends StatelessWidget {
const IconDemo({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.home),
SizedBox(width: 16),
Icon(
Icons.favorite,
color: Colors.red,
size: 48,
),
],
),
),
),
);
}
}The first icon uses the defaults. The second sets color and size directly. Both constructors are const, which is possible because Icons.* values are compile-time constants.
The parameters that matter
| Parameter | Type | What it does |
|---|---|---|
| `icon` | `IconData?` | The glyph to draw. Required positional argument. |
| `size` | `double?` | Width and height of the square box, in logical pixels. |
| `color` | `Color?` | Fill color of the glyph. |
| `semanticLabel` | `String?` | Text that screen readers announce. |
| `textDirection` | `TextDirection?` | Used to mirror icons that flip in right-to-left languages. |
| `shadows` | `List<Shadow>?` | Draws shadows behind the glyph. |
| `fill`, `weight`, `grade`, `opticalSize` | `double?` | Axes of variable icon fonts. |
When you leave size or color as null, the widget asks the nearest IconTheme above it in the tree. If none sets a value, the size falls back to 24. The next chapter covers IconTheme in detail. For now, remember that a missing value is inherited, not zero.
Size is the box, not the glyph
size sets the square the icon occupies. The glyph is drawn inside that square with some internal padding. An Icon with size: 48 takes up 48 by 48 pixels of layout space, even though the visible shape is a little smaller. The widget does not respond to its parent's constraints the way an Image does. To make an icon fill a space, compute a size from the available room, for example with LayoutBuilder.
Variable font axes
fill, weight, grade, and opticalSize change the look of icons drawn from a variable font, such as the Material Symbols fonts. The built-in MaterialIcons font is not variable. Setting these values on Icons.* constants has no visible effect, which surprises many developers. Use them only after you have added a variable icon font yourself.
Choosing a style variant
Most Material icons exist in several styles. The style is part of the constant's name.
| Constant | Style |
|---|---|
| `Icons.favorite` | Filled |
| `Icons.favorite_border` or `Icons.favorite_outline` | Outline only |
| `Icons.favorite_rounded` | Rounded corners |
| `Icons.favorite_sharp` | Sharp corners |
Pick one family and keep it throughout the app. Mixing filled and outlined icons without a reason makes the interface look inconsistent. A common pattern is to use the outline for the off state and the filled glyph for the on state, as in a like button.
Icons that react to taps
Icon is purely visual. It has no tap handling, no focus, and no minimum touch size. Wrapping it in a GestureDetector works, but you lose ripple effects, keyboard focus, and the 48 by 48 touch target that Material recommends. Use IconButton instead.
import 'package:flutter/material.dart';
class LikeButton extends StatefulWidget {
const LikeButton({super.key});
@override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton> {
bool _liked = false;
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: () => setState(() => _liked = !_liked),
tooltip: _liked ? 'Remove like' : 'Like',
icon: Icon(
_liked ? Icons.favorite : Icons.favorite_border,
color: _liked ? Colors.red : null,
),
);
}
}Here color: null means "inherit", so the unliked icon takes the theme color. The tooltip also gives screen readers a label for the button.
Pairing icons with text
When an icon sits next to a label, put both in a Row. Set crossAxisAlignment to CrossAxisAlignment.center (the default) and add a SizedBox for the gap.
const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.place, size: 18),
SizedBox(width: 4),
Text('Lisbon'),
],
)For buttons, TextButton.icon, ElevatedButton.icon, and ListTile(leading: ...) already handle the spacing and the color. Prefer them over a hand-built Row.
Common errors and how to fix them
- The icon shows as an empty box or a missing glyph. The
MaterialIconsfont was not bundled. Check thatpubspec.yamlcontainsuses-material-design: trueunder theflutter:section, then runflutter pub getand restart the app. A hot reload does not pick up new fonts. - Cupertino icons do not appear.
CupertinoIconscomes from thecupertino_iconspackage. Add it todependenciesinpubspec.yaml. The standard project template includes it, but older or minimal projects may not. - An icon looks invisible. It may have the same color as its background, or an
IconThemeabove it may set an opacity or a transparent color. Setcolorexplicitly to test. - The icon is the wrong size inside a button.
IconButtonusesiconSizefor its child. Settingsizeon the innerIconoverrides it, and the button's padding then stays the same. Choose one place to set the size. - A release build lost some icons. Flutter removes unused glyphs from the icon font to shrink the app, a step called tree shaking. It works only when it can see the
IconDataat build time. If you build anIconDatafrom a runtime number, for exampleIconData(codeFromServer, fontFamily: 'MaterialIcons'), the build fails with an error about non-constantIconData. Either map server values toIcons.*constants with aswitch, or build with--no-tree-shake-iconsand accept a larger app.
An icon with no glyph
Passing null as the icon, Icon(null), draws nothing but still reserves the size by size box. This is useful for aligning rows where some entries have an icon and others do not, because every row keeps the same indent.
Summary
- An
Icondraws one glyph from an icon font, so it scales cleanly and takes its color fromcoloror the inheritedIconTheme. sizedefines a square layout box with a default of 24.- Choose filled, outlined, rounded, or sharp constants and stay consistent.
- Use
IconButtonfor anything the user can tap. - Enable
uses-material-design: trueand avoid runtime-builtIconDatato prevent missing glyphs and build errors.
Exercise
A teammate writes Icon(Icons.star, size: 40, color: Colors.amber) inside a GestureDetector to make a rating star tappable. Name two problems with this approach and give the widget you would use instead.
Show answer
The Icon gives no ripple feedback and no keyboard focus, and its touch area is only 40 by 40 pixels, below the 48 by 48 Material recommendation. It also has no tooltip or label for assistive technology unless you add semanticLabel yourself. Use IconButton with onPressed, a tooltip, and the Icon as its icon.
Exercise
Your release build shows blank squares for some icons, but the debug build looks fine, and the project builds without errors. List the first two things you check.
Show answer
First, confirm that pubspec.yaml has uses-material-design: true under flutter:, because the MaterialIcons font is only bundled when it is set. Second, check whether any IconData is created at runtime from a number or string rather than taken from an Icons.* constant. Tree shaking can drop glyphs it cannot see at build time. Replace such values with a Map of constants, or build with --no-tree-shake-icons.