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 cursor = widget.document.cursor;
  final container = widget.node as InlineContainerNode;
  final nodeId = widget.node.id;

  // Get the paragraph style (if applicable)
  final paragraph = widget.node is Paragraph ? widget.node as Paragraph : null;
  final style = paragraph?.getStyle();

  // Spacing: use the paragraph style as base, with fallback to document
  final styleSpacingBefore = style?.spacingBefore ?? 0.0;
  final styleSpacingAfter = style?.spacingAfter ?? 0.0;
  final spacingBefore = widget.applyParagraphSpacing
      ? (styleSpacingBefore > 0 ? styleSpacingBefore : widget.document.pendingSpacingBefore)
      : 0.0;
  final spacingAfter = widget.applyParagraphSpacing
      ? (styleSpacingAfter > 0 ? styleSpacingAfter : widget.document.pendingSpacingAfter)
      : 0.0;

  // Get the selection range for this node from the document
  final selRange = widget.document.getSelectionRangeForNode(nodeId);

  // Build a widget for each inline FluentImage (e.g. inside Link).
  // The order must match that of `collectInlineImages` used in the
  // RenderObject to align WidgetSpan placeholders.
  final currentVersion = widget.document.contentVersion;
  if (_cachedInlineImages == null ||
      _cachedInlineImagesVersion != currentVersion) {
    _cachedInlineImages = collectInlineImages(container);
    _cachedInlineImagesVersion = currentVersion;
  }
  final imageWidgets = _cachedInlineImages!.map((img) {
    // Use InlineImageWidget for inline images to maintain inline behavior
    return InlineImageWidget(node: img, document: widget.document);
  }).toList();

  final spellAnnotations = _spell?.annotationsForNode(nodeId) ?? const [];
  final commentAnnotations = _comment?.commentsForNode(nodeId) ?? const [];
  final selectedCommentId = _comment?.selectedCommentId;

  // Calculate padding for indentation (24px per level)
  final indentLevel = (widget.node as Paragraph).indent;
  final indentPadding = indentLevel * 24.0;

  return RepaintBoundary(
    child: Padding(
      padding: EdgeInsets.only(
        left: indentPadding,
        top: spacingBefore,
        bottom: spacingAfter,
      ),
      child: Listener(
      onPointerDown: (event) {
        if (event.buttons == 2) { // kSecondaryMouseButton
          _isSecondaryTap = true;
        }
      },
      child: GestureDetector(
        onTapDown: (details) {
          if (_isSecondaryTap) {
            _isSecondaryTap = false;
            return; // Do not move cursor / collapse selection on right-click
          }

          widget.document.requestEditorFocus();

          final now = DateTime.now();
          final isConsecutiveTap = _lastTapTime != null &&
              now.difference(_lastTapTime!).inMilliseconds < 300 &&
              _lastTapPosition != null &&
              (details.globalPosition - _lastTapPosition!).distance < 30;

          if (isConsecutiveTap) {
            _tapCount++;
          } else {
            _tapCount = 1;
          }
          _lastTapTime = now;
          _lastTapPosition = details.globalPosition;

          final renderObject = _renderWidgetKey.currentContext?.findRenderObject();
          if (renderObject is RenderBox) {
            final localPosition = renderObject.globalToLocal(details.globalPosition);

            if (_tapCount >= 3) {
              // Triple tap: select the entire logical line
              _tapCount = 0;
              _savedSelection = null;
              widget.document.eventHandler.onTripleTapWithPosition(
                localPosition, renderObject, widget);
            } else if (_tapCount == 2) {
              _savedSelection = null;
              widget.document.eventHandler.onDoubleTapWithPosition(
                localPosition, renderObject, widget);
            } else {
              // If this paragraph has an active selection, defer cursor
              // movement to onTap. This way a long-press does not destroy
              // the selection before the context menu is shown.
              final selRange = widget.document.selectionManager.getRangeForNode(widget.node.id);
              final hasSelection = selRange != null &&
                  !widget.document.selectionManager.isCollapsed;
              if (hasSelection) {
                _savedSelection = selRange;
                // Do not call onTapDownWithPosition – keep selection intact.
              } else {
                _savedSelection = null;
                widget.document.eventHandler.onTapDownWithPosition(
                  localPosition, renderObject, widget);
              }
            }
          }
        },
        onTap: () {
          widget.document.requestEditorFocus();
          // Activate virtual keyboard on mobile (only for confirmed short-taps)
          widget.document.requestMobileKeyboardFocus();
          // Tap completed inside an active selection: now collapse and move cursor.
          if (_savedSelection != null && _lastTapPosition != null && mounted) {
            final renderObject = _renderWidgetKey.currentContext?.findRenderObject();
            if (renderObject is RenderBox) {
              final localPosition = renderObject.globalToLocal(_lastTapPosition!);
              widget.document.eventHandler.onTapDownWithPosition(
                localPosition, renderObject, widget);
            }
            _savedSelection = null;
          }
        },
        onSecondaryTapUp: (details) {
          _isSecondaryTap = false;
          _onSecondaryTap(details);
        },
        onLongPressStart: (details) {
          _onLongPress(details);
        },
        child: FParagraphRenderWidget(
        key: _renderWidgetKey,
        node: container,
        registry: widget.document.paragraphRegistry,
        lineHeight: style?.lineHeight ?? widget.document.pendingLineHeight,
        textAlign: _parseTextAlign((widget.node as Paragraph).textAlign),
        shrinkWrap: widget.shrinkWrap,
        paragraphStyle: style, // Pass the style for fallbacks
        defaultTextColor: Theme.of(context).colorScheme.onSurface,
        anchorFragmentId: cursor.anchorId,
        anchorLocalOffset: cursor.anchorOffset,
        focusFragmentId: cursor.isCollapsed ? null : cursor.focusId,
        focusLocalOffset: cursor.isCollapsed ? null : cursor.focusOffset,
        // Pass the selection from the document (if present for this node)
        selAnchorFragmentId: selRange?.startFrag,
        selAnchorLocalOffset: selRange?.startOff,
        selFocusFragmentId: selRange?.endFrag,
        selFocusLocalOffset: selRange?.endOff,
        spellAnnotations: spellAnnotations,
        commentAnnotations: commentAnnotations,
        selectedCommentId: selectedCommentId,
        children: imageWidgets,
      ),
    ),
  ),
),
);
}