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) {
  /// Find whether device is mobile or Laptop.
  _findDevice(context);
  final bool isPdfLoaded = _pdfViewerController.pageCount > 0 &&
      _originalWidth != null &&
      _originalHeight != null;
  _pdfDimension =
      _childKey.currentContext?.findRenderObject()?.paintBounds.size ??
          Size.zero;
  return isPdfLoaded
      ? Listener(
          onPointerSignal: _handlePointerSignal,
          onPointerDown: _handlePointerDown,
          onPointerMove: _handlePointerMove,
          onPointerUp: _handlePointerUp,
          child: Container(
            color: _pdfViewerThemeData!.backgroundColor ??
                _effectiveThemeData!.backgroundColor ??
                (_themeData!.colorScheme.brightness == Brightness.light
                    ? const Color(0xFFD6D6D6)
                    : const Color(0xFF303030)),
            child: LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
              _viewportConstraints = constraints;
              if (_viewportSize != _viewportConstraints.biggest) {
                _viewportSize = _viewportConstraints.biggest;
                _getTileImage();
              }
              double totalHeight = 0.0;
              _isKeyPadRaised = View.of(context).viewInsets.bottom != 0.0;
              Size viewportDimension = _viewportConstraints.biggest;
              // Viewport dimension without keypad height.
              Size? visibleViewportDimension;
              if (_isKeyPadRaised) {
                visibleViewportDimension = viewportDimension;
                _iskeypadClosed = true;
                double keyPadHeight = EdgeInsets.fromViewPadding(
                        View.of(context).viewInsets,
                        View.of(context).devicePixelRatio)
                    .bottom;
                if (keyPadHeight > 0) {
                  if (viewportDimension.height + keyPadHeight !=
                      _viewportHeight) {
                    keyPadHeight = _viewportHeight - viewportDimension.height;
                  } else {
                    _viewportHeight = viewportDimension.height + keyPadHeight;
                  }
                }

                viewportDimension = Size(viewportDimension.width,
                    viewportDimension.height + keyPadHeight);
              } else {
                if (_iskeypadClosed) {
                  viewportDimension =
                      Size(viewportDimension.width, _viewportHeight);
                  _iskeypadClosed = false;
                } else {
                  _viewportHeight = viewportDimension.height;
                }
              }
              if (!isBookmarkViewOpen) {
                _otherContextHeight ??= MediaQuery.of(context).size.height -
                    _viewportConstraints.maxHeight;
              }
              if (_deviceOrientation == Orientation.landscape) {
                _viewportHeightInLandscape ??=
                    MediaQuery.of(context).size.height - _otherContextHeight!;
              }
              if (!_pdfDimension.isEmpty) {
                if (_scrollDirection == PdfScrollDirection.vertical) {
                  _maxScrollExtent = _pdfDimension.height -
                      (viewportDimension.height /
                          _pdfViewerController.zoomLevel);
                } else {
                  _maxScrollExtent = _pdfDimension.width -
                      (viewportDimension.width /
                          _pdfViewerController.zoomLevel);
                }
              }
              _viewportGlobalRect = _getViewportGlobalRect();
              Widget child;
              final List<Widget> children = List<Widget>.generate(
                  _pdfViewerController.pageCount, (int index) {
                if (index == 0) {
                  totalHeight = 0;
                }
                if (_originalWidth!.length !=
                    _pdfViewerController.pageCount) {
                  return _getEmptyContainer();
                }
                final int pageIndex = index + 1;
                final Size calculatedSize = _calculateSize(
                    BoxConstraints(maxWidth: _viewportConstraints.maxWidth),
                    _originalWidth![index].toDouble(),
                    _originalHeight![index].toDouble(),
                    _viewportConstraints.maxWidth,
                    viewportDimension.height);
                if (!_pdfPagesKey.containsKey(pageIndex)) {
                  _pdfPagesKey[pageIndex] = GlobalKey();
                }
                if (kIsDesktop && !_isMobileView) {
                  if (_originalWidth![index].toDouble() > _maxPdfPageWidth !=
                      null) {
                    _maxPdfPageWidth = _originalWidth![index].toDouble();
                  }
                }

                Widget page = PdfPageView(
                    _pdfPagesKey[pageIndex]!,
                    _viewportGlobalRect,
                    viewportDimension,
                    widget.interactionMode,
                    _plugin.documentID,
                    calculatedSize.width,
                    calculatedSize.height,
                    widget.pageSpacing,
                    _document,
                    _pdfPages,
                    index,
                    _pdfViewerController,
                    _effectiveUndoController,
                    widget.maxZoomLevel,
                    widget.enableDocumentLinkAnnotation,
                    widget.enableTextSelection,
                    _textSelectionHelper,
                    _handleTextSelectionChanged,
                    widget.onHyperlinkClicked,
                    _handleTextSelectionDragStarted,
                    _handleTextSelectionDragEnded,
                    widget.currentSearchTextHighlightColor,
                    widget.otherSearchTextHighlightColor,
                    _textCollection,
                    _isMobileView,
                    _pdfViewerController._pdfTextSearchResult,
                    _pdfScrollableStateKey,
                    _singlePageViewKey,
                    _scrollDirection,
                    _handlePdfPagePointerDown,
                    _handlePdfPagePointerMove,
                    _handlePdfPagePointerUp,
                    isBookmarkViewOpen ? '' : _pageTextExtractor[index],
                    widget.pageLayoutMode == PdfPageLayoutMode.single,
                    _textDirection!,
                    widget.canShowHyperlinkDialog,
                    widget.enableHyperlinkNavigation,
                    _isAndroidTV,
                    widget.canShowPageLoadingIndicator,
                    widget.canShowSignaturePadDialog,
                    _handlePageTap,
                    _pdfViewerController._formFields,
                    _pdfViewerController._annotations,
                    _selectedAnnotation,
                    _onAnnotationSelectionChanged,
                    _onStickyNoteAnnotationDoubleTapped);
                final double pageSpacing =
                    index == _pdfViewerController._pageCount - 1
                        ? 0.0
                        : widget.pageSpacing;
                _pdfPages[pageIndex] =
                    PdfPageInfo(totalHeight, calculatedSize);
                if (_isMobileWebView ?? false) {
                  page = Visibility(
                    visible: _isPageVisible(pageIndex),
                    replacement:
                        _getReplacementWidget(pageIndex, calculatedSize),
                    child: page,
                  );
                }
                // In RTL direction, the last page is rendered at Offset.zero.
                // Hence, the we are interchanging the page offset value of all the pages.
                if (_textDirection == TextDirection.rtl &&
                    widget.pageLayoutMode == PdfPageLayoutMode.continuous &&
                    _scrollDirection == PdfScrollDirection.horizontal &&
                    _pdfViewerController.pageCount == pageIndex) {
                  for (int i = 1; i <= _pdfViewerController.pageCount; i++) {
                    _pdfPages[i]!.pageOffset =
                        totalHeight - _pdfPages[i]!.pageOffset;
                  }
                }

                if (_scrollDirection == PdfScrollDirection.vertical &&
                    widget.pageLayoutMode != PdfPageLayoutMode.single) {
                  totalHeight += calculatedSize.height + pageSpacing;
                } else {
                  totalHeight += calculatedSize.width + pageSpacing;
                }
                _updateScrollDirectionChange(
                    _offsetBeforeOrientationChange, pageIndex, totalHeight);
                _updateOffsetOnOrientationChange(
                    _offsetBeforeOrientationChange, pageIndex, totalHeight);
                return page;
              });
              Widget? pdfContainer;
              if (!_isLoaded) {
                Future<dynamic>.delayed(Duration.zero, () async {
                  if (_document != null && widget.onDocumentLoaded != null) {
                    _isDocumentLoadInitiated = false;
                    widget.onDocumentLoaded!(
                        PdfDocumentLoadedDetails(_document!));
                  }
                  _checkMount();
                  _isLoaded = true;
                });
              }
              if (widget.pageLayoutMode == PdfPageLayoutMode.single) {
                _pageController = PageController(
                    initialPage: _pdfViewerController._pageNumber - 1);
                pdfContainer = MouseRegion(
                  cursor: _cursor,
                  onHover: (PointerHoverEvent details) {
                    if (widget.interactionMode == PdfInteractionMode.pan &&
                        _cursor != SystemMouseCursors.grab) {
                      setState(() {
                        _cursor = SystemMouseCursors.grab;
                      });
                    } else if (widget.interactionMode ==
                            PdfInteractionMode.selection &&
                        _cursor != SystemMouseCursors.basic) {
                      setState(() {
                        _cursor = SystemMouseCursors.basic;
                      });
                    }
                  },
                  child: SinglePageView(
                      _singlePageViewKey,
                      _pdfViewerController,
                      _transformationController,
                      _pageController,
                      _handleSinglePageViewPageChanged,
                      _interactionUpdate,
                      viewportDimension,
                      visibleViewportDimension,
                      widget.maxZoomLevel,
                      widget.canShowPaginationDialog,
                      widget.canShowScrollHead,
                      widget.canShowScrollStatus,
                      _pdfPages,
                      _isMobileView,
                      widget.enableDoubleTapZooming,
                      widget.interactionMode,
                      _isScaleEnabled,
                      _handleSinglePageViewZoomLevelChanged,
                      _handleDoubleTap,
                      _handlePdfOffsetChanged,
                      isBookmarkViewOpen,
                      _textDirection!,
                      _isTablet,
                      _scrollDirection,
                      _getTileImage,
                      children),
                );
                if (_isSinglePageViewPageChanged &&
                    _renderedImages
                        .contains(_pdfViewerController.pageNumber)) {
                  Future<dynamic>.delayed(Duration.zero, () async {
                    if (_pageController.hasClients) {
                      _pdfViewerController._scrollPositionX = 0;
                    }
                    if (!_isSearchStarted) {
                      _pdfPagesKey[_pdfViewerController.pageNumber]
                          ?.currentState
                          ?.focusNode
                          .requestFocus();
                    }
                    if (getSelectedTextLines().isNotEmpty &&
                        getSelectedTextLines().first.pageNumber + 1 ==
                            _pdfViewerController.pageNumber) {
                      _pdfPagesKey[_pdfViewerController.pageNumber]
                          ?.currentState
                          ?.canvasRenderBox
                          ?.updateContextMenuPosition();
                    }
                    _isSinglePageViewPageChanged = false;
                  });
                }
              } else {
                final Size childSize = _getChildSize(viewportDimension);
                if (_scrollDirection == PdfScrollDirection.horizontal) {
                  child = Row(
                      key: _childKey,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: children);
                } else {
                  child = Column(
                      key: _childKey,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: children);
                }
                child = MouseRegion(
                  cursor: _cursor,
                  onHover: (PointerHoverEvent details) {
                    if (widget.interactionMode == PdfInteractionMode.pan &&
                        _cursor != SystemMouseCursors.grab) {
                      setState(() {
                        _cursor = SystemMouseCursors.grab;
                      });
                    } else if (widget.interactionMode ==
                            PdfInteractionMode.selection &&
                        _cursor != SystemMouseCursors.basic) {
                      setState(() {
                        _cursor = SystemMouseCursors.basic;
                      });
                    }
                  },
                  child: SizedBox(
                      height: childSize.height,
                      width: childSize.width,
                      child: child),
                );
                pdfContainer = PdfScrollable(
                  _transformationController,
                  widget.canShowPaginationDialog,
                  widget.canShowScrollStatus,
                  widget.canShowScrollHead,
                  _pdfViewerController,
                  _isMobileView,
                  _pdfDimension,
                  _totalImageSize,
                  viewportDimension,
                  visibleViewportDimension,
                  _handlePdfOffsetChanged,
                  _panEnabled,
                  widget.maxZoomLevel,
                  _minScale,
                  widget.enableDoubleTapZooming,
                  widget.interactionMode,
                  _maxPdfPageWidth,
                  _isScaleEnabled,
                  _maxScrollExtent,
                  _pdfPages,
                  _scrollDirection,
                  isBookmarkViewOpen,
                  _textDirection!,
                  child,
                  _getTileImage,
                  key: _pdfScrollableStateKey,
                  onDoubleTap: _handleDoubleTap,
                );
                // Updates current offset when scrollDirection change occurs.
                if (_isScrollDirectionChange) {
                  _pdfScrollableStateKey.currentState
                      ?.forcePixels(_scrollDirectionSwitchOffset);
                  _isScrollDirectionChange = false;
                }
              }
              WidgetsBinding.instance
                  .addPostFrameCallback((Duration timeStamp) {
                if (super.mounted && context.mounted) {
                  // call PdfViewerController methods after ScrollController attached.
                  _isDocumentLoaded();

                  // If the text direction is changed, then jump to the current page to avoid the abrupt change in the view.
                  if (_isTextDirectionChanged) {
                    _isTextDirectionChanged = false;
                    _pdfViewerController
                        .jumpToPage(_pdfViewerController.pageNumber);
                  }
                }
              });
              return Stack(
                children: <Widget>[
                  pdfContainer,
                  BookmarkView(_bookmarkKey, _document, _pdfViewerController,
                      _handleBookmarkViewChanged, _textDirection!),
                ],
              );
            }),
          ),
        )
      : (_hasError
          ? _isEncryptedDocument
              ? _showWebPasswordDialogue()
              : _getEmptyContainer()
          : _getEmptyLinearProgressView());
}