build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  final isEnabled = onChanged != null;
  final isDark = GlassTheme.brightnessOf(context) == Brightness.dark;
  final highContrast = MediaQuery.maybeHighContrastOf(context) ?? false;
  final effectiveSurfaceStyle = surfaceStyle ??
      InheritedGlassSurfaceStyle.maybeOf(context) ??
      GlassSurfaceStyle.glass;
  final isSolid = effectiveSurfaceStyle == GlassSurfaceStyle.solid;

  Color resolve(Color c) => _resolveDynamicColor(c, isDark, highContrast);

  final resolvedColor = color != null ? resolve(color!) : null;
  final resolvedActiveColor = resolve(
    activeColor ?? CupertinoTheme.of(context).primaryColor,
  );

  // Native iOS 26/27: a disabled ON toggle desaturates to a muted neutral
  // shaded pill rather than vibrant accent fill, while staying visibly
  // distinct from a disabled OFF pill. Both glass tintColor and solid
  // Opacity(0.5) attenuate disabled fills by 0.5, so passing 0.32 (light) /
  // 0.56 (dark) lands both modes at the calibrated 0.16 / 0.28 rest alpha.
  final Color? disabledOnFill = (!isEnabled && value)
      ? resolve(CupertinoColors.systemGrey)
          .withValues(alpha: isDark ? 0.56 : 0.32)
      : null;

  final Color effectiveForeground;
  if (!isEnabled) {
    effectiveForeground = foregroundColor != null
        ? resolve(foregroundColor!)
        : resolve(CupertinoColors.label);
  } else if (value) {
    effectiveForeground = activeForegroundColor != null
        ? resolve(activeForegroundColor!)
        : (resolvedActiveColor.computeLuminance() > 0.55
            ? CupertinoColors.black
            : CupertinoColors.white);
  } else {
    final explicitFg =
        foregroundColor != null ? resolve(foregroundColor!) : null;
    if (explicitFg != null) {
      effectiveForeground = explicitFg;
    } else if (isSolid && resolvedColor != null && resolvedColor.a > 0.5) {
      effectiveForeground = resolvedColor.computeLuminance() > 0.55
          ? CupertinoColors.black
          : CupertinoColors.white;
    } else {
      effectiveForeground = resolve(CupertinoColors.label);
    }
  }

  final defaultLabelStyle = TextStyle(
    fontSize: 17.0,
    fontWeight: FontWeight.w400,
    letterSpacing: -0.41,
    color: effectiveForeground,
  );
  final effectiveLabelStyle = labelStyle != null
      ? defaultLabelStyle.merge(labelStyle)
      : defaultLabelStyle;

  final isIconOnly = child == null && icon != null && label == null;
  final effectivePadding = padding ??
      (height != null
          ? EdgeInsetsDirectional.symmetric(horizontal: isIconOnly ? 13 : 12)
          : (isIconOnly ? _defaultIconOnlyPadding : _defaultTextPadding));

  final Widget innerContent;
  if (child != null) {
    innerContent = DefaultTextStyle.merge(
      style: defaultLabelStyle,
      child: IconTheme.merge(
        data: IconThemeData(color: effectiveForeground, size: iconSize),
        child: child!,
      ),
    );
  } else if (isIconOnly) {
    innerContent = IconTheme(
      data: IconThemeData(color: effectiveForeground, size: iconSize),
      child: icon!,
    );
  } else {
    innerContent = Row(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (icon != null) ...[
          IconTheme(
            data: IconThemeData(color: effectiveForeground, size: iconSize),
            child: icon!,
          ),
          SizedBox(width: spacing),
        ],
        Flexible(
          child: Text(
            label!,
            textDirection: textDirection,
            textAlign: TextAlign.center,
            // A label that does not fit wraps rather than being cut, as
            // a SwiftUI button's does at large text sizes. Only a fixed
            // height keeps it to one line.
            maxLines: height == null ? null : 1,
            overflow:
                height == null ? TextOverflow.clip : TextOverflow.ellipsis,
            style: effectiveLabelStyle,
          ),
        ),
      ],
    );
  }

  final paddedContent = ConstrainedBox(
    constraints: BoxConstraints(
      minWidth: width ?? (isIconOnly ? 44.0 : 0.0),
      minHeight: height ?? minHeight,
    ),
    child: Padding(
      padding: effectivePadding,
      child: Center(
        widthFactor: width == null ? 1.0 : null,
        heightFactor: height == null ? 1.0 : null,
        child: innerContent,
      ),
    ),
  );

  // One option of a mutually exclusive set reads as a radio button; Apple
  // platforms read its state from `selected`, as Flutter's own radio
  // buttons report it there.
  final exclusive = semanticsInMutuallyExclusiveGroup;
  final reportsSelected = exclusive &&
      (defaultTargetPlatform == TargetPlatform.iOS ||
          defaultTargetPlatform == TargetPlatform.macOS);

  final button = GlassButton.custom(
    onTap: isEnabled ? _handleTap : _noOp,
    enabled: isEnabled,
    isToggled: exclusive ? null : value,
    isChecked: exclusive ? value : null,
    isSelected: reportsSelected ? value : null,
    label: semanticLabel ?? '',
    width: width,
    height: height,
    shape: shape,
    style: (value && isEnabled)
        ? GlassButtonStyle.prominent
        : GlassButtonStyle.filled,
    surfaceStyle: surfaceStyle,
    color: value ? (isSolid ? disabledOnFill : null) : color,
    tintColor:
        value ? (isEnabled ? resolvedActiveColor : disabledOnFill) : null,
    settings: settings,
    useOwnLayer: useOwnLayer,
    quality: quality,
    platformViewBackdrop: platformViewBackdrop,
    interactionScale: isEnabled ? interactionScale : 1.0,
    stretch: isEnabled ? stretch : 0.0,
    glowRadius: isEnabled ? glowRadius : 0.0,
    isStationary: !isEnabled,
    anchorStretch: anchorStretch,
    anchorStretchSettings: anchorStretchSettings,
    focusNode: focusNode,
    autofocus: autofocus,
    canRequestFocus: canRequestFocus,
    child: paddedContent,
  );

  // The 34 pt capsule is smaller than the 44 x 44 pt minimum target: the
  // semantics node extends around it to that size, and the touch area as
  // far as the parent's bounds allow, while the toggle keeps its size in
  // the layout.
  return _ToggleTapTarget(child: button);
}