import 'package:flutter/material.dart'; import '../adaptive/platform.dart'; /// Whether icon-only actions show a visible caption: on touch devices, which /// have no hover to reveal a tooltip. Desktop keeps icons with tooltips. bool showsActionCaptions(BuildContext context) => !prefersCompactHitTargets(context); /// A toolbar action that is an [IconButton] with its tooltip on desktop and, /// on touch, the icon over a short visible [caption] in the same 48 dp tall /// target, so a phone user can read what it does without long-pressing. /// /// [label] is the full accessible name (and desktop tooltip); [caption] is /// the short word drawn under the icon, defaulting to [label]. class LabelledIconButton extends StatelessWidget { const LabelledIconButton({ super.key, required this.icon, required this.label, required this.onPressed, this.caption, this.isSelected = false, this.iconSize, this.child, }); final IconData icon; final String label; final String? caption; final VoidCallback? onPressed; final bool isSelected; final double? iconSize; /// Replaces the icon glyph (a progress indicator or a badged icon). final Widget? child; @override Widget build(BuildContext context) { final glyph = child ?? Icon(icon, size: iconSize); if (!showsActionCaptions(context)) { return IconButton( tooltip: label, isSelected: isSelected, constraints: const BoxConstraints( minWidth: kMinInteractiveDimension, minHeight: kMinInteractiveDimension, ), onPressed: onPressed, icon: glyph, ); } final theme = Theme.of(context); final color = onPressed == null ? theme.disabledColor : isSelected ? theme.colorScheme.primary : theme.colorScheme.onSurfaceVariant; return Semantics( button: true, enabled: onPressed != null, selected: isSelected, label: label, excludeSemantics: true, child: InkResponse( onTap: onPressed, radius: kMinInteractiveDimension * 0.75, child: ConstrainedBox( constraints: const BoxConstraints( minWidth: kMinInteractiveDimension, minHeight: kMinInteractiveDimension, maxHeight: kMinInteractiveDimension, // A long caption scales down rather than widening the toolbar. maxWidth: kMinInteractiveDimension + 8, ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: FittedBox( fit: BoxFit.scaleDown, child: Column( mainAxisSize: MainAxisSize.min, children: [ IconTheme.merge( data: IconThemeData(color: color, size: 22), child: glyph, ), const SizedBox(height: 2), Text( caption ?? label, maxLines: 1, style: theme.textTheme.labelSmall?.copyWith(color: color), ), ], ), ), ), ), ), ); } }