build method
Describes the part of the user interface represented by this widget.
The framework calls this method in a number of different situations. For example:
- After calling initState.
- After calling didUpdateWidget.
- After receiving a call to setState.
- After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).
- After calling deactivate and then reinserting the State object into the tree at another location.
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) {
assert(debugCheckHasShadTheme(context));
final theme = ShadTheme.of(context);
final effectiveDecoration = theme.decoration
.merge(theme.selectTheme.decoration)
.merge(widget.decoration);
final decorationHorizontalPadding =
(effectiveDecoration.border?.padding?.horizontal ?? 0.0) +
(effectiveDecoration.secondaryBorder?.padding?.horizontal ?? 0.0);
final effectivePadding =
widget.padding ??
theme.selectTheme.padding ??
const EdgeInsets.symmetric(horizontal: 12, vertical: 8);
final effectiveShowScrollToTopChevron =
widget.showScrollToTopChevron ??
theme.selectTheme.showScrollToTopChevron ??
true;
final effectiveShowScrollToBottomChevron =
widget.showScrollToBottomChevron ??
theme.selectTheme.showScrollToBottomChevron ??
true;
final effectivePopoverReverseDuration =
widget.popoverReverseDuration ??
theme.selectTheme.popoverReverseDuration ??
Duration.zero;
final effectiveAnchor =
widget.anchor ??
theme.selectTheme.anchor ??
const ShadAnchorAuto(
offset: Offset(0, 4),
fallback: ShadAnchorAuto(
offset: Offset(0, -4),
followerAnchor: Alignment.topCenter,
targetAnchor: Alignment.topCenter,
),
);
final effectiveEffects = widget.effects ?? theme.selectTheme.effects;
final effectiveShadows = widget.shadows ?? theme.selectTheme.shadows;
final effectiveFilter = widget.filter ?? theme.selectTheme.filter;
final isMultiSelect = widget.selectedOptionsBuilder != null;
// make effectiveText listen to controller changes
final effectiveText = ListenableBuilder(
listenable: controller,
builder: (context, child) {
final Widget result;
final TextStyle resultDefaultTextStyle;
if (controller.value.isNotEmpty) {
// The value shown in the trigger belongs to the *page*, not the
// menu: `optionTheme.selectedTextStyle` carries the menu palette's
// highlight foreground, which is unreadable on the trigger the
// moment menus are inverted or bold.
resultDefaultTextStyle = theme.textTheme.muted.fallback(
color: theme.colorScheme.foreground,
);
switch (isMultiSelect) {
case true:
result = widget.selectedOptionsBuilder!(
context,
controller.value.toList(),
);
case false:
result = widget.selectedOptionBuilder!(
context,
controller.value.first,
);
}
} else {
assert(
widget.placeholder != null,
'placeholder must not be null when value is null',
);
resultDefaultTextStyle =
widget.placeholderStyle ??
theme.selectTheme.placeholderStyle ??
theme.textTheme.muted.fallback(
color: theme.colorScheme.foreground,
);
result = widget.placeholder!;
}
return DefaultTextStyle(style: resultDefaultTextStyle, child: result);
},
);
// `cn-select-trigger-icon`: `text-muted-foreground size-4`.
final effectiveTrailing =
widget.trailing ??
Icon(
LucideIcons.chevronDown,
size: 16,
color: theme.colorScheme.mutedForeground,
);
final effectiveMinWidth =
widget.minWidth ?? theme.selectTheme.minWidth ?? kDefaultSelectMinWidth;
final effectiveMaxWidth =
widget.maxWidth ?? theme.selectTheme.maxWidth ?? double.infinity;
final effectiveMaxHeight =
widget.maxHeight ??
theme.selectTheme.maxHeight ??
kDefaultSelectMaxHeight;
final effectiveMinHeight = widget.minHeight ?? theme.selectTheme.minHeight;
final effectiveOptionsPadding =
widget.optionsPadding ??
theme.selectTheme.optionsPadding ??
const EdgeInsets.all(4);
// Everything rendered *inside* the options popover reads in the menu
// palette, not the page's: an inverted menu keeps its own foreground.
// The option rows' resting colour carries it.
final menuForeground =
theme.optionTheme.textStyle?.color ??
theme.colorScheme.popoverForeground;
final search = switch (widget.variant) {
ShadSelectVariant.primary || ShadSelectVariant.multiple => null,
ShadSelectVariant.search ||
ShadSelectVariant.multipleWithSearch => Column(
mainAxisSize: MainAxisSize.min,
children: [
widget.search ??
ShadInput(
focusNode: searchFocusNode,
leading: Padding(
padding: const EdgeInsets.only(right: 8),
child: Icon(
LucideIcons.search,
size: 16,
color: menuForeground,
),
),
style: (theme.inputTheme.style ?? theme.textTheme.muted)
.copyWith(color: menuForeground),
padding:
widget.searchPadding ??
theme.selectTheme.searchPadding ??
const EdgeInsets.all(12),
placeholder: widget.searchPlaceholder,
decoration: ShadDecoration.none,
onChanged: widget.onSearchChanged,
onSubmitted: widget.onSearchSubmitted,
),
widget.searchDivider ??
const ShadSeparator.horizontal(margin: EdgeInsets.zero),
],
),
};
return ListenableBuilder(
listenable: searchFocusNode,
builder: (context, child) {
return CallbackShortcuts(
bindings: searchFocusNode.hasFocus
? const {}
: {
const SingleActivator(LogicalKeyboardKey.enter):
desktopTogglePopover,
const SingleActivator(LogicalKeyboardKey.space):
desktopTogglePopover,
const SingleActivator(LogicalKeyboardKey.escape):
popoverController.hide,
},
child: child!,
);
},
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: LayoutBuilder(
builder: (context, constraints) {
final calculatedMinWidth =
max(effectiveMinWidth, constraints.minWidth) -
decorationHorizontalPadding;
final effectiveConstraints = BoxConstraints(
minWidth: calculatedMinWidth,
maxWidth: effectiveMaxWidth,
);
// Built lazily inside the `popover:` builder below rather than
// here. This LayoutBuilder wraps the whole select — anchor
// included — so it re-runs on every layout pass of the *closed*
// select. `widget.options` is a lazy Iterable, so materialising it
// eagerly meant constructing every option widget on each of those
// passes. ShadCalendar's year dropdown passes 201 options, each
// building a DateFormat.
Widget buildOptions() {
if (widget.options != null) {
return SingleChildScrollView(
padding: effectiveOptionsPadding,
controller: scrollController,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: widget.options!.toList(),
),
);
}
return ListView.builder(
padding: effectiveOptionsPadding,
controller: scrollController,
itemCount: widget.itemCount,
shrinkWrap: widget.shrinkWrap ?? false,
itemBuilder: (context, index) {
return widget.optionsBuilder?.call(context, index);
},
);
}
final Widget select = ShadDisabled(
disabled: !widget.enabled,
child: ShadFocusable(
autofocus: widget.autofocus,
onFocusChange: widget.onFocusChange,
canRequestFocus: widget.enabled,
focusNode: focusNode,
builder: (context, focused, child) {
final decorated = ShadDecorator(
focused: focused,
decoration: effectiveDecoration,
child: child,
);
if (effectiveMinHeight == null) return decorated;
// The reference pins the trigger's height (`h-9` and
// friends), border included, and centres the content in
// it. Constraining outside the decorator counts the
// border's implicit padding in, like CSS border-box.
return ConstrainedBox(
constraints: BoxConstraints(minHeight: effectiveMinHeight),
child: decorated,
);
},
child: ShadGestureDetector(
cursor: SystemMouseCursors.click,
behavior: HitTestBehavior.opaque,
onTapDown: (details) {
if (widget.onPressed != null) {
widget.onPressed!();
return;
}
FocusScope.of(context).unfocus();
if (details.kind == PointerDeviceKind.touch) {
popoverController.toggle();
} else {
desktopTogglePopover();
}
},
child: ConstrainedBox(
constraints: effectiveConstraints,
child: Padding(
padding: effectivePadding,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: effectiveText),
effectiveTrailing,
],
),
),
),
),
),
);
final scrollToTopChild = effectiveShowScrollToTopChevron
? ValueListenableBuilder(
valueListenable: showScrollToTop,
builder: (context, show, child) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: show
? MouseRegion(
onEnter: (_) {
shouldAnimateToTop = true;
animateToTop();
},
onExit: (_) => shouldAnimateToTop = false,
child: Container(
width: calculatedMinWidth,
padding: const EdgeInsets.symmetric(
vertical: 4,
),
child: Icon(
LucideIcons.chevronUp,
size: 16,
color: menuForeground,
),
),
)
: const SizedBox(),
);
},
)
: null;
final scrollToBottomChild = effectiveShowScrollToBottomChevron
? ValueListenableBuilder(
valueListenable: showScrollToBottom,
builder: (context, show, child) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: show
? MouseRegion(
onEnter: (_) {
shouldAnimateToBottom = true;
animateToBottom();
},
onExit: (_) => shouldAnimateToBottom = false,
child: Container(
width: calculatedMinWidth,
padding: const EdgeInsets.symmetric(
vertical: 4,
),
child: Icon(
LucideIcons.chevronDown,
size: 16,
color: menuForeground,
),
),
)
: const SizedBox(),
);
},
)
: null;
return ShadProvider(
data: this as ShadSelectState<dynamic>,
notifyUpdate: (_) => true,
child: ShadPopover(
groupId: widget.groupId,
padding: EdgeInsets.zero,
controller: popoverController,
anchor: effectiveAnchor,
closeOnTapOutside: widget.closeOnTapOutside,
effects: effectiveEffects,
reverseDuration: effectivePopoverReverseDuration,
shadows: effectiveShadows,
filter: effectiveFilter,
// The options surface is a menu, and menus can carry their
// own palette; without this it would inherit the page
// popover's decoration.
decoration: theme.selectTheme.popoverDecoration,
popover: (_) {
// Seed showScrollToBottom/showScrollToTop once the popover
// has been laid out. Guarded: this builder can run many
// times per open, and an unguarded callback queued one
// closure per build.
if (!_scrollChevronSyncScheduled) {
_scrollChevronSyncScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollChevronSyncScheduled = false;
if (!mounted) return;
if (scrollController.hasClients) {
showScrollToBottom.value =
scrollController.offset <
scrollController.position.maxScrollExtent;
showScrollToTop.value = scrollController.offset > 0;
}
});
}
Widget effectiveColumn = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (search != null) Flexible(child: search),
if (widget.header != null)
Flexible(child: widget.header!),
?scrollToTopChild,
Flexible(child: buildOptions()),
?scrollToBottomChild,
if (widget.footer != null)
Flexible(child: widget.footer!),
],
);
if (widget.optionsBuilder == null) {
effectiveColumn = IntrinsicWidth(child: effectiveColumn);
}
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: effectiveMaxHeight,
minWidth: calculatedMinWidth,
maxWidth: effectiveMaxWidth,
),
child: effectiveColumn,
);
},
child: select,
),
);
},
),
),
);
}