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) {
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
var effectiveTextStyle = widget.style;
if (widget.style == null || widget.style!.inherit) {
effectiveTextStyle = defaultTextStyle.style.merge(widget.style);
}
final linkText =
(_expanded ? widget.collapseText : widget.expandText) ?? '';
final linkColor = widget.linkColor ??
widget.prefixStyle?.color ??
const Color(0xFF4666F6);
final linkTextStyle = effectiveTextStyle!
.merge(widget.prefixStyle)
.copyWith(color: linkColor);
final prefixText =
widget.prefixText != null && widget.prefixText!.isNotEmpty
? '${widget.prefixText} '
: '';
final link = TextSpan(
children: [
if (!_expanded)
TextSpan(
text: '\u2026 ',
style: widget.linkEllipsis ? linkTextStyle : effectiveTextStyle,
recognizer: widget.linkEllipsis ? _linkTapGestureRecognizer : null,
),
if (linkText.isNotEmpty)
TextSpan(
style: effectiveTextStyle,
children: <TextSpan>[
if (_expanded)
const TextSpan(
text: ' ',
),
TextSpan(
text: linkText,
style: linkTextStyle,
recognizer: _linkTapGestureRecognizer,
),
],
),
],
);
final prefix = extractLinksAndTags(prefixText);
final text = extractLinksAndTags(widget.text);
final content = TextSpan(
children: <TextSpan>[...prefix, ...text],
style: effectiveTextStyle,
);
Widget result = LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
assert(constraints.hasBoundedWidth);
final double maxWidth = constraints.maxWidth;
final textAlign =
widget.textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start;
final textDirection =
widget.textDirection ?? Directionality.of(context);
final textScaleFactor =
widget.textScaleFactor ?? MediaQuery.textScaleFactorOf(context);
final locale = Localizations.maybeLocaleOf(context);
TextPainter textPainter = TextPainter(
text: link,
textAlign: textAlign,
textDirection: textDirection,
textScaleFactor: textScaleFactor,
maxLines: widget.maxLines,
locale: locale,
);
textPainter.layout(minWidth: constraints.minWidth, maxWidth: maxWidth);
final linkSize = textPainter.size;
textPainter.text = content;
textPainter.layout(minWidth: constraints.minWidth, maxWidth: maxWidth);
final textSize = textPainter.size;
TextSpan textSpan;
if (textPainter.didExceedMaxLines) {
final position = textPainter.getPositionForOffset(Offset(
textSize.width - linkSize.width,
textSize.height,
));
final endOffset =
(textPainter.getOffsetBefore(position.offset) ?? 0) -
prefixText.length;
final recognizer =
(_expanded ? widget.collapseOnTextTap : widget.expandOnTextTap)
? _linkTapGestureRecognizer
: null;
String resultText;
if (!_expanded) {
var response =
LMChatTaggingHelper.convertRouteToTagAndUserMap(widget.text);
List<LMChatTagViewData> userTags = response['userTags'];
resultText = response['text'];
// final lineCount = textPainter.computeLineMetrics().length;
final nCount = '\n'.allMatches(resultText).length + 1;
if (resultText.length > 300 && nCount <= 4) {
resultText = resultText.substring(0, max(endOffset, 0));
} else {
resultText = resultText.substring(0, max(endOffset, 0));
}
resultText = LMChatTaggingHelper.encodeString(resultText, userTags);
} else {
resultText = widget.text;
}
final text = _textSegments.isNotEmpty
? TextSpan(
children: _buildTextSpans(
_expanded ? _textSegments : parseText(resultText),
effectiveTextStyle!,
recognizer),
)
: TextSpan(
children: extractLinksAndTags(resultText),
);
textSpan = TextSpan(
style: effectiveTextStyle,
children: <TextSpan>[
...prefix,
text,
link,
],
);
} else {
textSpan = content;
}
final richText = SelectableText.rich(
textSpan,
textDirection: textDirection,
textAlign: textAlign,
textScaleFactor: textScaleFactor,
enableInteractiveSelection: widget.enableSelection,
style: widget.style,
);
if (widget.animation) {
return AnimatedSize(
duration:
widget.animationDuration ?? const Duration(milliseconds: 200),
curve: widget.animationCurve ?? Curves.fastLinearToSlowEaseIn,
alignment: Alignment.topLeft,
child: richText);
}
return richText;
},
);
if (widget.semanticsLabel != null) {
result = Semantics(
textDirection: widget.textDirection,
label: widget.semanticsLabel,
child: ExcludeSemantics(
child: result,
),
);
}
return result;
}