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 auth = context.authResolve(permission, target: TAuthTarget.tile, onDenied: onDenied);
  if (auth.isHidden) return const SizedBox.shrink();
  final onTap = auth.isDisabled ? null : this.onTap;
  final colors = context.colors;
  final effectiveCrossAxisAlignment = crossAxisAlignment ?? CrossAxisAlignment.center;
  final effectiveIcon = leading ?? ((imageUrl != null && imageUrl!.isNotEmpty) ? null : icon);

  final effectiveIconSize = iconSize ?? size.icon;
  final effectiveIconPadding = iconPadding ?? (size.hPad > 0 || size.vPad > 0 ? size.padding : const EdgeInsets.all(8));
  final effectiveIconBorderRadius = iconBorderRadius ?? BorderRadius.circular(size.radius);
  final effectiveSpacing = spacing ?? size.spacing;

  final defaultBg = (isHovered || isExpanded) ? colors.primaryContainer.withAlpha(128) : colors.onSurface.withAlpha(13);
  final defaultIconColor = (isHovered || isExpanded) ? colors.primary : colors.onSurfaceVariant;

  Color resolvedIconColor;
  if (isExpanded && expandedIconColor != null) {
    resolvedIconColor = expandedIconColor!;
  } else if (isHovered && hoveredIconColor != null) {
    resolvedIconColor = hoveredIconColor!;
  } else {
    resolvedIconColor = iconColor ?? defaultIconColor;
  }

  Widget? leadingWidget;
  if (effectiveIcon != null) {
    if (effectiveIcon is Widget) {
      leadingWidget = IconTheme(
        data: IconThemeData(
          color: resolvedIconColor,
          size: effectiveIconSize,
        ),
        child: effectiveIcon,
      );
    } else {
      Color resolvedBg;
      if (isExpanded && expandedIconBackgroundColor != null) {
        resolvedBg = expandedIconBackgroundColor!;
      } else if (isHovered && hoveredIconBackgroundColor != null) {
        resolvedBg = hoveredIconBackgroundColor!;
      } else {
        resolvedBg = iconBackgroundColor ?? defaultBg;
      }

      leadingWidget = Container(
        padding: effectiveIconPadding,
        decoration: BoxDecoration(
          color: resolvedBg,
          borderRadius: effectiveIconBorderRadius,
        ),
        child: TIcon.raw(
          effectiveIcon,
          size: effectiveIconSize,
          color: resolvedIconColor,
        ),
      );
    }
  } else if (imageUrl != null && imageUrl!.isNotEmpty) {
    leadingWidget = ClipRRect(
      borderRadius: effectiveIconBorderRadius,
      child: TImage(
        url: imageUrl,
        size: effectiveIconSize,
        disabled: true,
        forceCache: forceCache,
      ),
    );
  }

  final effectiveTitleStyle = _resolveTitleStyle(colors);

  final titleChild = titleWidget ??
      (title != null
          ? Text(
              title!,
              style: effectiveTitleStyle,
            )
          : const SizedBox.shrink());

  final subtitleFontSize = size.resolveSubtitleFontSize();
  final subtitleGap = size.resolveSubtitleGap();

  final defaultSubtitleStyle = TextStyle(
    fontSize: subtitleFontSize,
    fontWeight: size.resolveSubtitleFontWeight(),
    color: colors.onSurfaceVariant,
  );

  final effectiveSubtitleStyle = subtitleStyle != null ? defaultSubtitleStyle.merge(subtitleStyle) : defaultSubtitleStyle;

  final subtitleChild = subtitleWidget ??
      (subtitle != null
          ? Text(
              subtitle!,
              style: effectiveSubtitleStyle,
            )
          : null);

  final descFontSize = size.resolveDescFontSize();
  final descGap = size.resolveDescGap();

  final defaultDescStyle = TextStyle(
    fontSize: descFontSize,
    fontWeight: FontWeight.w300,
    color: colors.onSurfaceVariant,
  );

  final effectiveDescStyle = descStyle != null ? defaultDescStyle.merge(descStyle) : defaultDescStyle;

  final descChild = descWidget ??
      (desc != null
          ? Text(
              desc!,
              style: effectiveDescStyle,
            )
          : null);

  return _HeadCenterHost(
    builder: (headCenter) => LayoutBuilder(
      builder: (context, constraints) {
        final availableWidth = constraints.maxWidth;
        final hasLeading = leadingWidget != null;
        final (leadingWidth, leadingHeight) = _resolveLeadingDimensions(
          leading: effectiveIcon ?? (imageUrl != null && imageUrl!.isNotEmpty ? imageUrl : null),
          defaultSize: effectiveIconSize,
          iconPadding: effectiveIconPadding,
        );

        bool descInColumn = false;
        if (descChild != null) {
          if (!hasLeading || leadingHeight <= 0) {
            descInColumn = true;
          } else {
            final direction = Directionality.maybeOf(context) ?? TextDirection.ltr;
            final textScaler = MediaQuery.maybeTextScalerOf(context) ?? TextScaler.noScaling;

            final trailingReserve = trailing != null ? 48.0 : 0.0;
            final paddingReserve = padding?.horizontal ?? 0.0;
            final leadingReserve = hasLeading ? leadingWidth + effectiveSpacing : 0.0;

            final maxTextWidth = availableWidth.isFinite
                ? math.max(0.0, availableWidth - leadingReserve - trailingReserve - paddingReserve)
                : double.infinity;

            // Desc spans under the trailing widget, so it only loses the leading/padding width.
            final descTextWidth =
                availableWidth.isFinite ? math.max(0.0, availableWidth - leadingReserve - paddingReserve) : double.infinity;

            double measureHeight(String? text, TextStyle style, [double? width]) {
              final maxWidth = width ?? maxTextWidth;
              if (text == null || text.isEmpty || maxWidth <= 0) return 0.0;
              final painter = TextPainter(
                text: TextSpan(text: text, style: style),
                textDirection: direction,
                textScaler: textScaler,
              );
              painter.layout(maxWidth: maxWidth);
              final h = painter.height;
              painter.dispose();
              return h;
            }

            final titleH = title != null ? measureHeight(title, effectiveTitleStyle) : (titleWidget != null ? size.font * 1.3 : 0.0);

            final subH = subtitle != null
                ? measureHeight(subtitle, effectiveSubtitleStyle)
                : (subtitleWidget != null ? subtitleFontSize * 1.3 : 0.0);

            final descH =
                desc != null ? measureHeight(desc, effectiveDescStyle, descTextWidth) : (descWidget != null ? descFontSize * 1.3 : 0.0);

            double requiredTextHeight = titleH;
            if (subtitleChild != null) {
              requiredTextHeight += subtitleGap + subH;
            }
            requiredTextHeight += descGap + descH;

            // If in image height then below subtitle else go below image
            descInColumn = requiredTextHeight <= leadingHeight;
          }
        }

        final headChildren = <Widget>[
          titleChild,
          if (subtitleChild != null) ...[
            SizedBox(height: subtitleGap),
            subtitleChild,
          ],
        ];

        // Trailing sits beside title/subtitle only, so desc gets the full text width.
        final trailingBesideHead = trailing != null && !iconOnTop;

        final columnChildren = <Widget>[
          if (trailingBesideHead)
            _TileHead(
              title: titleChild,
              subtitle: subtitleChild,
              trailing: trailing!,
              subtitleGap: subtitleGap,
              gap: 8,
              rowGap: 3,
              trailingAbove: trailingAboveOnOverflow,
              textCenter: crossAxisAlignment == null ? headCenter : null,
            )
          else
            ...headChildren,
          if (highlights != null && highlights!.isNotEmpty) ...[
            SizedBox(height: subtitleGap + 4),
            THighlights(items: highlights!, fontSize: subtitleFontSize),
          ],
          if (descChild != null && descInColumn) ...[
            SizedBox(height: descGap),
            descChild,
          ],
        ];

        final textColumn = Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: iconOnTop ? (crossAxisAlignment ?? CrossAxisAlignment.start) : CrossAxisAlignment.start,
          children: columnChildren,
        );

        final Widget topRow;
        if (iconOnTop && leadingWidget != null) {
          topRow = Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.start,
            children: [
              if (trailing != null)
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [leadingWidget, const Spacer(), trailing!],
                )
              else
                leadingWidget,
              SizedBox(height: effectiveSpacing),
              textColumn,
            ],
          );
        } else {
          topRow = Row(
            mainAxisSize: trailing != null ? MainAxisSize.max : MainAxisSize.min,
            crossAxisAlignment:
                (trailingBesideHead && crossAxisAlignment == null) ? CrossAxisAlignment.start : effectiveCrossAxisAlignment,
            children: [
              if (leadingWidget != null) ...[
                if (trailingBesideHead && crossAxisAlignment == null)
                  ValueListenableBuilder<double?>(
                    valueListenable: headCenter,
                    child: leadingWidget,
                    builder: (_, c, child) => c == null
                        ? child!
                        : Transform.translate(
                            offset: Offset(0, c),
                            child: FractionalTranslation(translation: const Offset(0, -0.5), child: child),
                          ),
                  )
                else
                  leadingWidget,
                SizedBox(width: effectiveSpacing),
              ],
              if (trailing != null) Expanded(child: textColumn) else Flexible(child: textColumn),
              if (trailing != null && iconOnTop) trailing!,
            ],
          );
        }

        Widget content;
        if (descChild != null && !descInColumn) {
          content = Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              topRow,
              SizedBox(height: descGap),
              descChild,
            ],
          );
        } else {
          content = topRow;
        }

        if (values != null && values!.isNotEmpty) {
          content = Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              content,
              SizedBox(height: valuesSpacing ?? 16.0),
              TKeyValueSection(
                values: values!,
                mode: valuesMode ?? TKeyValueMode.inlineFlow,
              ),
            ],
          );
        }

        if (padding != null) {
          content = Padding(padding: padding!, child: content);
        }

        if (onTap != null) {
          return InkWell(
            onTap: onTap,
            borderRadius: borderRadius ?? BorderRadius.circular(8),
            child: content,
          );
        }

        return content;
      },
    ),
  );
}