StatelessWidget classabstract
A widget that does not require mutable state.
A stateless widget is a widget that describes part of the user interface bybuilding a constellation of other widgets that describe the user interfacemore concretely. The building process continues recursively until thedescription of the user interface is fully concrete (e.g., consistsentirely ofRenderObjectWidgets, which describe concreteRenderObjects).
Stateless widget are useful when the part of the user interface you aredescribing does not depend on anything other than the configurationinformation in the object itself and theBuildContext in which the widgetis inflated. For compositions that can change dynamically, e.g. due tohaving an internal clock-driven state, or depending on some system state,consider usingStatefulWidget.
Performance considerations
Thebuild method of a stateless widget is typically only called in threesituations: the first time the widget is inserted in the tree, when thewidget's parent changes its configuration (seeElement.rebuild), and whenanInheritedWidget it depends on changes.
If a widget's parent will regularly change the widget's configuration, or ifit depends on inherited widgets that frequently change, then it is importantto optimize the performance of thebuild method to maintain a fluidrendering performance.
There are several techniques one can use to minimize the impact ofrebuilding a stateless widget:
Minimize the number of nodes transitively created by the build method andany widgets it creates. For example, instead of an elaborate arrangementofRows,Columns,Paddings, andSizedBoxes to position a singlechild in a particularly fancy manner, consider using just anAlign or aCustomSingleChildLayout. Instead of an intricate layering of multipleContainers and withDecorations to draw just the right graphicaleffect, consider a singleCustomPaint widget.
Use
constwidgets where possible, and provide aconstconstructor forthe widget so that users of the widget can also do so.Consider refactoring the stateless widget into a stateful widget so thatit can use some of the techniques described atStatefulWidget, such ascaching common parts of subtrees and usingGlobalKeys when changing thetree structure.
If the widget is likely to get rebuilt frequently due to the use ofInheritedWidgets, consider refactoring the stateless widget intomultiple widgets, with the parts of the tree that change being pushed tothe leaves. For example instead of building a tree with four widgets, theinner-most widget depending on theTheme, consider factoring out thepart of the build function that builds the inner-most widget into its ownwidget, so that only the inner-most widget needs to be rebuilt when thetheme changes.
When trying to create a reusable piece of UI, prefer using a widgetrather than a helper method. For example, if there was a function used tobuild a widget, aState.setState call would require Flutter to entirely rebuild the returned wrapping widget. If aWidget was used instead, Flutter would be able to efficiently re-render only those parts that really need to be updated. Even better, if the created widget is
const, Flutter would short-circuit most of the rebuild work.
This video gives more explanations on whyconst constructors are importantand why aWidget is better than a helper method.
GreenFrog.Normally, widgets have more constructor arguments, each of which correspondsto afinal property.
class GreenFrog extends StatelessWidget { const GreenFrog({ super.key }); @override Widget build(BuildContext context) { return Container(color: const Color(0xFF2DBD3A)); }}Frog which can be givena color and a child:class Frog extends StatelessWidget { const Frog({ super.key, this.color = const Color(0xFF2DBD3A), this.child, }); final Color color; final Widget? child; @override Widget build(BuildContext context) { return ColoredBox(color: color, child: child); }}By convention, widget constructors only use named arguments. Also byconvention, the first argument iskey, and the last argument ischild,children, or the equivalent.
See also:
- StatefulWidget andState, for widgets that can build differentlyseveral times over their lifetime.
- InheritedWidget, for widgets that introduce ambient state that canbe read by descendant widgets.
- Inheritance
- Object
- DiagnosticableTree
- Widget
- StatelessWidget
- Implementers
- AboutDialog
- AboutListTile
- ActionChip
- AdaptiveTextSelectionToolbar
- AlertDialog
- AnimatedIcon
- Autocomplete
- BackButtonIcon
- Badge
- Builder
- ButtonBar
- CallbackShortcuts
- Card
- CheckboxListTile
- CheckboxMenuButton
- CheckedModeBanner
- Chip
- ChoiceChip
- CircleAvatar
- CloseButtonIcon
- Container
- CupertinoAdaptiveTextSelectionToolbar
- CupertinoDesktopTextSelectionToolbar
- CupertinoFormRow
- CupertinoFormSection
- CupertinoLinearActivityIndicator
- CupertinoListSection
- CupertinoListTileChevron
- CupertinoMagnifier
- CupertinoNavigationBarBackButton
- CupertinoPickerDefaultSelectionOverlay
- CupertinoPopupSurface
- CupertinoSpellCheckSuggestionsToolbar
- CupertinoTabBar
- CupertinoTextSelectionToolbar
- CupertinoTheme
- DataTable
- DefaultTextEditingShortcuts
- DesktopTextSelectionToolbar
- DesktopTextSelectionToolbarButton
- DeviceOrientationBuilder
- Dialog
- DisplayFeatureSubScreen
- Divider
- Drawer
- DrawerButtonIcon
- DrawerHeader
- DropdownMenuItem
- EndDrawerButtonIcon
- ExcludeFocus
- ExcludeFocusTraversal
- FilterChip
- FloatingActionButton
- FlutterLogo
- GestureDetector
- GridPaper
- GridTile
- GridTileBar
- HeroMode
- HtmlElementView
- Icon
- IconButton
- ImageIcon
- IndexedStack
- InkResponse
- InputChip
- InspectorButton
- KeyboardListener
- KeyedSubtree
- ListTile
- Magnifier
- MaterialButton
- MenuBar
- ModalBarrier
- NavigationBar
- NavigationDestination
- NavigationDrawer
- NavigationDrawerDestination
- NavigationIndicator
- NavigationToolbar
- OrientationBuilder
- PageStorage
- Placeholder
- PlatformSelectableRegionContextMenu
- PositionedDirectional
- PreferredSize
- RadioMenuButton
- RawMagnifier
- RawView
- ReorderableDragStartListener
- SafeArea
- Scrollbar
- ScrollView
- SimpleDialog
- SimpleDialogOption
- SingleChildScrollView
- SliverConstrainedCrossAxis
- SliverFillRemaining
- SliverFillViewport
- SliverPersistentHeader
- SliverResizingHeader
- SliverSafeArea
- SliverVisibility
- Spacer
- SpellCheckSuggestionsToolbar
- StatelessLeakingWidget
- StretchEffect
- Switch
- SwitchListTile
- Tab
- TableCell
- TabPageSelectorIndicator
- Text
- TextSelectionToolbar
- TextSelectionToolbarTextButton
- Theme
- ToggleButtons
- TooltipVisibility
- TwoDimensionalScrollView
- UnconstrainedBox
- VerticalDivider
- ViewAnchor
- Visibility
Constructors
- StatelessWidget({Key?key})
- Initializes
keyfor subclasses.const
Properties
Methods
- build(
BuildContextcontext)→Widget - Describes the part of the user interface represented by this widget.
- createElement(
)→StatelessElement - Creates aStatelessElement to manage this widget's location in the tree.override
- debugDescribeChildren(
)→List< DiagnosticsNode> - Returns a list ofDiagnosticsNode objects describing this node'schildren.inherited
- debugFillProperties(
DiagnosticPropertiesBuilderproperties)→ void - Add additional properties associated with the node.inherited
- noSuchMethod(
Invocationinvocation)→ dynamic - Invoked when a nonexistent method or property is accessed.inherited
- toDiagnosticsNode(
{String?name,DiagnosticsTreeStyle?style})→DiagnosticsNode - Returns a debug representation of the object that is used by debuggingtools and byDiagnosticsNode.toStringDeep.inherited
- toString(
{DiagnosticLevelminLevel =DiagnosticLevel.info})→String - A string representation of this object.inherited
- toStringDeep(
{StringprefixLineOne ='',String?prefixOtherLines,DiagnosticLevelminLevel =DiagnosticLevel.debug,intwrapWidth =65})→String - Returns a string representation of this node and its descendants.inherited
- toStringShallow(
{Stringjoiner =', ',DiagnosticLevelminLevel =DiagnosticLevel.debug})→String - Returns a one-line detailed description of the object.inherited
- toStringShort(
)→String - A short, textual description of this widget.inherited
Operators
- operator ==(
Objectother)→bool - The equality operator.inherited