build method

  1. @override
Widget build(
  1. BuildContext context

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;

  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> {
  // ...
  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.


Widget build(BuildContext context) {
  final SegmentedButtonThemeData theme = SegmentedButtonTheme.of(context);
  final SegmentedButtonThemeData defaults = _SegmentedButtonDefaultsM3(context);
  final TextDirection direction = Directionality.of(context);

  const Set<MaterialState> enabledState = <MaterialState>{};
  const Set<MaterialState> disabledState = <MaterialState>{ MaterialState.disabled };
  final Set<MaterialState> currentState = _enabled ? enabledState : disabledState;

  P? effectiveValue<P>(P? Function(ButtonStyle? style) getProperty) {
    late final P? widgetValue  = getProperty(;
    late final P? themeValue   = getProperty(;
    late final P? defaultValue = getProperty(;
    return widgetValue ?? themeValue ?? defaultValue;

  P? resolve<P>(MaterialStateProperty<P>? Function(ButtonStyle? style) getProperty, [Set<MaterialState>? states]) {
    return effectiveValue(
      (ButtonStyle? style) => getProperty(style)?.resolve(states ?? currentState),

  ButtonStyle segmentStyleFor(ButtonStyle? style) {
    return ButtonStyle(
      textStyle: style?.textStyle,
      backgroundColor: style?.backgroundColor,
      foregroundColor: style?.foregroundColor,
      overlayColor: style?.overlayColor,
      surfaceTintColor: style?.surfaceTintColor,
      elevation: style?.elevation,
      padding: style?.padding,
      iconColor: style?.iconColor,
      iconSize: style?.iconSize,
      shape: const MaterialStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()),
      mouseCursor: style?.mouseCursor,
      visualDensity: style?.visualDensity,
      tapTargetSize: style?.tapTargetSize,
      animationDuration: style?.animationDuration,
      enableFeedback: style?.enableFeedback,
      alignment: style?.alignment,
      splashFactory: style?.splashFactory,

  final ButtonStyle segmentStyle = segmentStyleFor(;
  final ButtonStyle segmentThemeStyle = segmentStyleFor(;
  final Widget? selectedIcon = widget.showSelectedIcon
    ? widget.selectedIcon ?? theme.selectedIcon ?? defaults.selectedIcon
    : null;

  Widget buttonFor(ButtonSegment<T> segment) {
    final Widget label = segment.label ?? segment.icon ?? const SizedBox.shrink();
    final bool segmentSelected = widget.selected.contains(segment.value);
    final Widget? icon = (segmentSelected && widget.showSelectedIcon)
      ? selectedIcon
      : segment.label != null
        ? segment.icon
        : null;
    final MaterialStatesController controller = statesControllers.putIfAbsent(segment, () => MaterialStatesController());
    controller.update(MaterialState.selected, segmentSelected);

    final Widget button = icon != null
      ? TextButton.icon(
          style: segmentStyle,
          statesController: controller,
          onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null,
          icon: icon,
          label: label,
      : TextButton(
          style: segmentStyle,
          statesController: controller,
          onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null,
          child: label,

    final Widget buttonWithTooltip = segment.tooltip != null
      ? Tooltip(
          message: segment.tooltip,
          child: button,
      : button;

    return MergeSemantics(
      child: Semantics(
        checked: segmentSelected,
        inMutuallyExclusiveGroup: widget.multiSelectionEnabled ? null : true,
        child: buttonWithTooltip,

  final OutlinedBorder resolvedEnabledBorder = resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape, disabledState) ?? const RoundedRectangleBorder();
  final OutlinedBorder resolvedDisabledBorder = resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape, disabledState)?? const RoundedRectangleBorder();
  final BorderSide enabledSide = resolve<BorderSide?>((ButtonStyle? style) => style?.side, enabledState) ?? BorderSide.none;
  final BorderSide disabledSide = resolve<BorderSide?>((ButtonStyle? style) => style?.side, disabledState) ?? BorderSide.none;
  final OutlinedBorder enabledBorder = resolvedEnabledBorder.copyWith(side: enabledSide);
  final OutlinedBorder disabledBorder = resolvedDisabledBorder.copyWith(side: disabledSide);
  final VisualDensity resolvedVisualDensity = segmentStyle.visualDensity ?? segmentThemeStyle.visualDensity ?? Theme.of(context).visualDensity;
  final EdgeInsetsGeometry resolvedPadding = resolve<EdgeInsetsGeometry?>((ButtonStyle? style) => style?.padding, enabledState) ??;
  final MaterialTapTargetSize resolvedTapTargetSize = segmentStyle.tapTargetSize ?? segmentThemeStyle.tapTargetSize ?? Theme.of(context).materialTapTargetSize;
  final double fontSize = resolve<TextStyle?>((ButtonStyle? style) => style?.textStyle, enabledState)?.fontSize ?? 20.0;

  final List<Widget> buttons =;

  final Offset densityAdjustment = resolvedVisualDensity.baseSizeAdjustment;
  const double textButtonMinHeight = 40.0;

  final double adjustButtonMinHeight = textButtonMinHeight + densityAdjustment.dy;
  final double effectiveVerticalPadding = resolvedPadding.vertical + densityAdjustment.dy * 2;
  final double effectedButtonHeight = max(fontSize + effectiveVerticalPadding, adjustButtonMinHeight);
  final double tapTargetVerticalPadding = switch (resolvedTapTargetSize) {
    MaterialTapTargetSize.shrinkWrap => 0.0,
    MaterialTapTargetSize.padded => max(0, kMinInteractiveDimension + densityAdjustment.dy - effectedButtonHeight)

  return Material(
    type: MaterialType.transparency,
    elevation: resolve<double?>((ButtonStyle? style) => style?.elevation)!,
    shadowColor: resolve<Color?>((ButtonStyle? style) => style?.shadowColor),
    surfaceTintColor: resolve<Color?>((ButtonStyle? style) => style?.surfaceTintColor),
    child: TextButtonTheme(
      data: TextButtonThemeData(style: segmentThemeStyle),
      child: _SegmentedButtonRenderWidget<T>(
        tapTargetVerticalPadding: tapTargetVerticalPadding,
        segments: widget.segments,
        enabledBorder: _enabled ? enabledBorder : disabledBorder,
        disabledBorder: disabledBorder,
        direction: direction,
        children: buttons,