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 in a number of different situations. For example:

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, the given BuildContext, and the internal state of this State object.

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. The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

Design discussion

Why is the build method on State, and not StatefulWidget?

Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.

For example, AnimatedWidget is a subclass of StatefulWidget that introduces an abstract Widget build(BuildContext context) method for its subclasses to implement. If StatefulWidget already had a build method that took a State argument, AnimatedWidget would be forced to provide its State object to subclasses even though its State object is an internal implementation detail of AnimatedWidget.

Conceptually, StatelessWidget could also be implemented as a subclass of StatefulWidget in a similar manner. If the build method were on StatefulWidget rather than State, that would not be possible anymore.

Putting the build function on State rather than StatefulWidget also helps avoid a category of bugs related to closures implicitly capturing this. If you defined a closure in a build function on a StatefulWidget, that closure would implicitly capture this, which is the current widget instance, and would have the (immutable) fields of that instance in scope:

// (this is not valid Flutter code)
class MyButton extends StatefulWidgetX {
  MyButton({super.key, required this.color});

  final Color color;

  @override
  Widget build(BuildContext context, State state) {
    return SpecialWidget(
      handler: () { print('color: $color'); },
    );
  }
}

For example, suppose the parent builds MyButton with color being blue, the $color in the print function refers to blue, as expected. Now, suppose the parent rebuilds MyButton with green. The closure created by the first build still implicitly refers to the original widget and the $color still prints blue even through the widget has been updated to green; should that closure outlive its widget, it would print outdated information.

In contrast, with the build function on the State object, closures created during build implicitly capture the State instance instead of the widget instance:

class MyButton extends StatefulWidget {
  const MyButton({super.key, this.color = Colors.teal});

  final Color color;
  // ...
}

class MyButtonState extends State<MyButton> {
  // ...
  @override
  Widget build(BuildContext context) {
    return SpecialWidget(
      handler: () { print('color: ${widget.color}'); },
    );
  }
}

Now when the parent rebuilds MyButton with green, the closure created by the first build still refers to State object, which is preserved across rebuilds, but the framework has updated that State object's widget property to refer to the new MyButton instance and ${widget.color} prints green, as expected.

See also:

  • StatefulWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  final theme = ShadTheme.of(context);
  final effectiveTextStyle = theme.textTheme.muted
      .copyWith(
        color: theme.colorScheme.foreground,
      )
      .merge(theme.inputTheme.style)
      .merge(widget.style);

  final effectiveDecoration =
      (theme.inputTheme.decoration ?? const ShadDecoration()).merge(
        widget.decoration,
      );

  final effectiveCursorColor =
      widget.cursorColor ??
      theme.inputTheme.cursorColor ??
      theme.colorScheme.primary;

  final effectiveCursorWidth =
      widget.cursorWidth ?? theme.inputTheme.cursorWidth ?? 2.0;

  final effectiveCursorHeight =
      widget.cursorHeight ?? theme.inputTheme.cursorHeight;

  final effectiveCursorRadius =
      widget.cursorRadius ?? theme.inputTheme.cursorRadius;

  final effectiveCursorOpacityAnimates =
      widget.cursorOpacityAnimates ??
      theme.inputTheme.cursorOpacityAnimates ??
      false;

  final effectivePadding =
      widget.padding ??
      theme.inputTheme.padding ??
      const EdgeInsets.symmetric(horizontal: 12, vertical: 8);

  final effectiveInputPadding =
      widget.inputPadding ?? theme.inputTheme.inputPadding ?? EdgeInsets.zero;

  final effectivePlaceholderStyle = theme.textTheme.muted
      .merge(theme.inputTheme.placeholderStyle)
      .merge(widget.placeholderStyle)
      .fallback(color: theme.colorScheme.mutedForeground);

  final defaultAlignment = Directionality.of(context) == TextDirection.rtl
      ? Alignment.topRight
      : Alignment.topLeft;

  final effectivePlaceholderAlignment =
      widget.placeholderAlignment ??
      theme.inputTheme.placeholderAlignment ??
      defaultAlignment;

  final effectiveAlignemnt =
      widget.alignment ?? theme.inputTheme.alignment ?? defaultAlignment;

  final effectiveMainAxisAlignment =
      widget.mainAxisAlignment ??
      theme.inputTheme.mainAxisAlignment ??
      MainAxisAlignment.start;

  final effectiveCrossAxisAlignment =
      widget.crossAxisAlignment ??
      theme.inputTheme.crossAxisAlignment ??
      CrossAxisAlignment.center;
  final effectiveMouseCursor =
      widget.mouseCursor ?? WidgetStateMouseCursor.textable;

  final effectiveGap = widget.gap ?? theme.inputTheme.gap ?? 8.0;

  final effectiveMaxLengthEnforcement =
      widget.maxLengthEnforcement ??
      LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(
        defaultTargetPlatform,
      );

  final effectiveInputFormatters = <TextInputFormatter>[
    ...?widget.inputFormatters,
    if (widget.maxLength != null)
      LengthLimitingTextInputFormatter(
        widget.maxLength,
        maxLengthEnforcement: effectiveMaxLengthEnforcement,
      ),
  ];

  final textScaler = MediaQuery.textScalerOf(context);

  final maxFontSize = max(
    (effectivePlaceholderStyle.fontSize ?? 0) *
        (effectivePlaceholderStyle.height ?? 0),
    (effectiveTextStyle.fontSize ?? 0) * (effectiveTextStyle.height ?? 0),
  );
  final maxFontSizeScaled = textScaler.scale(maxFontSize);

  final effectiveConstraints =
      widget.constraints ??
      theme.inputTheme.constraints ??
      BoxConstraints(minHeight: maxFontSizeScaled);

  final effectiveGroupId = widget.groupId ?? _groupId;

  final effectiveScrollbarPadding =
      widget.scrollbarPadding ?? theme.inputTheme.scrollbarPadding;

  final effectiveVerticalGap =
      widget.verticalGap ?? theme.inputTheme.verticalGap ?? 0.0;

  final effectiveUseBrowserContextMenu =
      widget.useBrowserContextMenu ??
      theme.inputTheme.useBrowserContextMenu ??
      kIsWeb;

  return ConstrainedBox(
    constraints: effectiveConstraints,
    child: ShadDisabled(
      disabled: !widget.enabled,
      child: _selectionGestureDetectorBuilder.buildGestureDetector(
        behavior: HitTestBehavior.translucent,
        child: ShadKeyboardToolbar(
          focusNode: effectiveFocusNode,
          toolbarBuilder: widget.keyboardToolbarBuilder,
          child: ValueListenableBuilder(
            valueListenable: hasFocus,
            builder: (context, focused, _) {
              return ValueListenableBuilder(
                valueListenable: effectiveController,
                builder: (context, textEditingValue, child) {
                  final Widget editableText;
                  final rawEditableTextContent = SizedBox(
                    width: widget.editableTextSize?.width,
                    height: widget.editableTextSize?.height,
                    child: EditableText(
                      showSelectionHandles: _showSelectionHandles,
                      key: editableTextKey,
                      controller: effectiveController,
                      obscuringCharacter: widget.obscuringCharacter,
                      readOnly: widget.readOnly,
                      focusNode: effectiveFocusNode,
                      // ! Selection handler section here
                      onSelectionChanged: _handleSelectionChanged,
                      selectionColor: focused
                          ? widget.selectionColor ??
                                theme.colorScheme.selection
                          : null,
                      selectionHeightStyle: widget.selectionHeightStyle,
                      selectionWidthStyle: widget.selectionWidthStyle,
                      contextMenuBuilder: effectiveUseBrowserContextMenu
                          ? null
                          : (widget.contextMenuBuilder ??
                                defaultContextMenuBuilder),
                      selectionControls: widget.selectionControls,
                      // ! End of selection handler
                      // ! section
                      mouseCursor: effectiveMouseCursor,
                      enableInteractiveSelection:
                          widget.enableInteractiveSelection,
                      style: effectiveTextStyle,
                      strutStyle: widget.strutStyle,
                      cursorColor: effectiveCursorColor,
                      cursorWidth: effectiveCursorWidth,
                      cursorHeight: effectiveCursorHeight,
                      cursorRadius: effectiveCursorRadius,
                      cursorOpacityAnimates: effectiveCursorOpacityAnimates,
                      backgroundCursorColor: const Color(
                        0xFF9E9E9E,
                      ),
                      keyboardType: widget.keyboardType,
                      keyboardAppearance:
                          widget.keyboardAppearance ?? theme.brightness,
                      textInputAction: widget.textInputAction,
                      textCapitalization: widget.textCapitalization,
                      autofocus: widget.autofocus,
                      obscureText: widget.obscureText,
                      autocorrect: widget.autocorrect,
                      magnifierConfiguration: widget.magnifierConfiguration,
                      smartDashesType: widget.smartDashesType,
                      smartQuotesType: widget.smartQuotesType,
                      enableSuggestions: widget.enableSuggestions,
                      maxLines: widget.maxLines,
                      minLines: widget.minLines,
                      expands: widget.expands,
                      onChanged: (v) {
                        _editableText?.hideToolbar();
                        widget.onChanged?.call(v);
                      },
                      onEditingComplete: widget.onEditingComplete,
                      onSubmitted: widget.onSubmitted,
                      onAppPrivateCommand: widget.onAppPrivateCommand,
                      inputFormatters: effectiveInputFormatters,
                      scrollPadding: widget.scrollPadding,
                      dragStartBehavior: widget.dragStartBehavior,
                      scrollPhysics: widget.scrollPhysics,
                      // Disable the internal scrollbars
                      // because there is already a
                      // Scrollbar above.
                      scrollBehavior:
                          ScrollConfiguration.of(
                            context,
                          ).copyWith(
                            scrollbars: false,
                            overscroll: false,
                          ),
                      autofillHints: widget.autofillHints,
                      clipBehavior: widget.clipBehavior,
                      restorationId: 'editable',
                      // ignore: deprecated_member_use
                      scribbleEnabled: widget.scribbleEnabled,
                      stylusHandwritingEnabled:
                          widget.stylusHandwritingEnabled,
                      enableIMEPersonalizedLearning:
                          widget.enableIMEPersonalizedLearning,
                      contentInsertionConfiguration:
                          widget.contentInsertionConfiguration,
                      undoController: widget.undoController,
                      spellCheckConfiguration: widget.spellCheckConfiguration,
                      textAlign: widget.textAlign,
                      onTapOutside: widget.onPressedOutside,
                      rendererIgnoresPointer: true,
                      showCursor: widget.showCursor,
                      groupId: effectiveGroupId,
                    ),
                  );
                  final rawEditableText = Semantics(
                    enabled: widget.enabled,
                    child: rawEditableTextContent,
                  );

                  if (widget.onLineCountChange != null) {
                    editableText = LayoutBuilder(
                      builder: (context, constraints) {
                        /// Fire onLineCountChange after the frame is rendered
                        /// This ensures that the line count is accurate, even for
                        /// resizes that happen outside of text changes.
                        WidgetsBinding.instance.addPostFrameCallback((
                          _,
                        ) {
                          if (mounted) {
                            fireOnLineCountChange(
                              effectiveController.text,
                              textScaler: textScaler,
                              constraints: constraints,
                              effectiveTextStyle: effectiveTextStyle,
                              effectiveCursorWidth: effectiveCursorWidth,
                            );
                          }
                        });
                        return rawEditableText;
                      },
                    );
                  } else {
                    editableText = rawEditableText;
                  }
                  return ShadDecorator(
                    decoration: effectiveDecoration,
                    focused: focused,
                    child: BoxyColumn(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (widget.top != null) widget.top!,
                        RawScrollbar(
                          thumbVisibility: isMultiline && isScrollable,
                          controller: effectiveScrollController,
                          padding: effectiveScrollbarPadding?.resolve(
                            Directionality.of(context),
                          ),
                          child: SingleChildScrollView(
                            controller: effectiveScrollController,
                            padding: effectivePadding,
                            physics: widget.scrollPhysics,
                            child: Row(
                              mainAxisAlignment: effectiveMainAxisAlignment,
                              crossAxisAlignment: effectiveCrossAxisAlignment,
                              children: [
                                if (widget.leading != null) widget.leading!,
                                Flexible(
                                  child: AbsorbPointer(
                                    // AbsorbPointer is needed when the input is
                                    // readOnly so the onTap callback is fired on
                                    // each part of the input
                                    absorbing: widget.readOnly,
                                    child: Padding(
                                      padding: effectiveInputPadding,
                                      child: Stack(
                                        children: [
                                          // placeholder
                                          if (textEditingValue.text.isEmpty &&
                                              widget.placeholder != null)
                                            Positioned.fill(
                                              child: Align(
                                                alignment:
                                                    effectivePlaceholderAlignment,
                                                child: DefaultTextStyle(
                                                  style:
                                                      effectivePlaceholderStyle,
                                                  child: widget.placeholder!,
                                                ),
                                              ),
                                            ),
                                          RepaintBoundary(
                                            child: UnmanagedRestorationScope(
                                              bucket: bucket,
                                              child: Align(
                                                alignment: effectiveAlignemnt,
                                                child: editableText,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                                if (widget.trailing != null) widget.trailing!,
                              ].separatedBy(SizedBox(width: effectiveGap)),
                            ),
                          ),
                        ),
                        if (widget.bottom != null) widget.bottom!,
                      ].separatedBy(SizedBox(height: effectiveVerticalGap)),
                    ),
                  );
                },
              );
            },
          ),
        ),
      ),
    ),
  );
}