Files
pipelines/app/lib/ui/adaptive/segmented_bar.dart
T
alan b90c7e2d1d Cheaper frosted-glass blurs: sigma 4 and one backdrop read per bar
Blur sigma 16 -> 4 keeps CanvasKit on its direct blur path; under the 84%
fill the look is unchanged (max 13/255 inside the pieces). SegmentedBar's
pieces share a BackdropGroup so Impeller reads the content behind them once.
Adds a scroll frame-time bench, a backdrop census and filler rows to the
full-app probe. CPU CanvasKit, 560x900: run timeline p50 31.8 -> 22.1 ms,
runs list 25.3 -> 19.9 ms.
2026-11-02 00:58:23 +00:00

385 lines
14 KiB
Dart

import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'segmented_bar_pieces.dart';
export 'segmented_bar_pieces.dart' show SegmentedBackButton, SegmentedPill;
/// The app's top bar: separate frosted-glass pieces floating over the page's
/// content, on a scrim of the page's background that fades out downwards.
///
/// From the leading edge: a round piece holding [leading] (the platform's
/// Back, implied as the stock bars do when [automaticallyImplyLeading]), a
/// pill with the [title] and an optional one-line [subtitle] that runs
/// [onTitlePressed] when given, and a pill holding the [actions] at the
/// trailing edge. The actions take their natural width first and the title
/// shrinks; only when the title is down to [minTitleShare] of the bar does
/// the first action ellipsise.
///
/// A page whose bar is mainly an input (Search) passes [titleWidget] instead:
/// it takes the title pill's place as one pill that fills the space beside
/// the leading piece (up to the widget's own width cap), with no title.
///
/// Only the pieces take taps: a tap between them reaches the content behind.
/// It works as a [Scaffold.appBar] (with `extendBodyBehindAppBar`) and a
/// [CupertinoPageScaffold.navigationBar], which inset the content by the
/// bar's height through [MediaQuery.paddingOf], so a page keeps its
/// scaffold's structure; [SegmentedBarOverlay] does the same anywhere else.
/// It handles the top safe area itself.
class SegmentedBar extends StatefulWidget
implements ObstructingPreferredSizeWidget {
const SegmentedBar({
super.key,
required this.cupertino,
required this.title,
this.titleWidget,
this.titleWidgetMaxWidth = double.infinity,
this.leading,
this.automaticallyImplyLeading = true,
this.subtitle,
this.subtitleIcon,
this.onTitlePressed,
this.expandableTitle = false,
this.titleAction,
this.titleSemanticLabel,
this.titleKey,
this.actions = const [],
this.backgroundColor,
this.pillColor,
this.foregroundColor,
this.bottomPadding = 8,
});
/// Which control family to draw. Required because the bar's reserved
/// height differs: a Cupertino navigation bar never scales its text, so it
/// reserves exactly its height, while a Material app bar grows with text.
final bool cupertino;
/// The title; empty shows no title pill unless there is a [subtitle].
final String title;
/// The bar's main pill when it is not a title: a search field and its
/// filters. It replaces the title pill (so [title], [subtitle] and
/// [onTitlePressed] are not drawn) and fills the width beside the leading
/// piece and any [actions], up to [titleWidgetMaxWidth].
final Widget? titleWidget;
/// The widest the [titleWidget] pill grows on a wide window; it starts at
/// the leading edge, so content below can line up with it.
final double titleWidgetMaxWidth;
/// The leading control, normally a [SegmentedBackButton].
final Widget? leading;
/// Whether to show the platform's Back (or close, on a full-screen dialog)
/// when [leading] is null and the route can go back.
final bool automaticallyImplyLeading;
final String? subtitle;
final IconData? subtitleIcon;
/// Makes the title pill a button (an information page, a picker).
final VoidCallback? onTitlePressed;
/// Lets the title expand over the content without changing bar clearance.
final bool expandableTitle;
/// An action shown inside the expanded title pill.
final Widget? titleAction;
final String? titleSemanticLabel;
/// The key of the title's button (or its content when not pressable).
final Key? titleKey;
final List<Widget> actions;
/// The bar's backdrop; defaults to the enclosing scaffold's background.
final Color? backgroundColor;
/// The pieces' fill; defaults to the host's raised surface role.
final Color? pillColor;
/// The title's color, for a bar over a dark backdrop.
final Color? foregroundColor;
/// Space between the pieces and the content below.
final double bottomPadding;
static const double _topPadding = 8;
/// The share of the bar the title keeps before the actions shrink.
static const double minTitleShare = 0.25;
/// Bar text grows with the reader's setting up to this factor, like the
/// stock app bar caps its title, so the bar never takes over the page.
static const double maxTextScale = 2;
@override
Size get preferredSize {
final piece = segmentedPieceHeight(cupertino);
if (cupertino) {
// CupertinoPageScaffold disables text scaling for its navigation bar
// and reserves exactly this height for it.
return Size.fromHeight(_topPadding + piece + bottomPadding);
}
// A Material scaffold only caps its app bar at this height and lets it
// size to its content: room for a title and subtitle at the largest
// text scale.
return Size.fromHeight(_topPadding + piece * maxTextScale + bottomPadding);
}
@override
// Content scrolls behind the bar; the scaffold insets it by the bar's
// height through the media padding instead.
bool shouldFullyObstruct(BuildContext context) => false;
Color _background(BuildContext context) {
if (backgroundColor case final color?) {
// A dynamic system colour (the grouped background) follows the theme.
return CupertinoDynamicColor.maybeResolve(color, context) ?? color;
}
if (cupertino) {
return context
.dependOnInheritedWidgetOfExactType<
CupertinoPageScaffoldBackgroundColor
>()
?.color ??
CupertinoTheme.of(context).scaffoldBackgroundColor;
}
return Scaffold.maybeOf(context)?.widget.backgroundColor ??
Theme.of(context).scaffoldBackgroundColor;
}
@override
State<SegmentedBar> createState() => _SegmentedBarState();
}
class _SegmentedBarState extends State<SegmentedBar> {
bool _expanded = false;
/// The expanded title is drawn in the overlay, anchored to the collapsed
/// pill: drawn inside the bar it would overflow the bar's bounds, where
/// its pipeline action could be seen but not tapped.
final _titleLink = LayerLink();
final _expandedTitle = OverlayPortalController();
/// The row's pieces sit side by side, so they share one read of the
/// content behind them. The expanded title overlaps the content below the
/// bar and is drawn later, in the overlay, so it reads its own.
final _piecesBackdrop = BackdropKey();
final _expandedTitleBackdrop = BackdropKey();
@override
void didUpdateWidget(covariant SegmentedBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.title != widget.title ||
oldWidget.subtitle != widget.subtitle) {
_expanded = false;
}
}
void _toggleTitle() {
// The portal stays attached once used and draws nothing while
// collapsed, so collapsing on a new run (during a rebuild) needs no
// overlay call.
if (!_expandedTitle.isShowing) _expandedTitle.show();
setState(() => _expanded = !_expanded);
}
@override
Widget build(BuildContext context) {
final cupertino = widget.cupertino;
final title = widget.title;
final titleWidget = widget.titleWidget;
final titleWidgetMaxWidth = widget.titleWidgetMaxWidth;
final leadingWidget = widget.leading;
final automaticallyImplyLeading = widget.automaticallyImplyLeading;
final subtitle = widget.subtitle;
final subtitleIcon = widget.subtitleIcon;
final onTitlePressed = widget.onTitlePressed;
final titleSemanticLabel = widget.titleSemanticLabel;
final titleKey = widget.titleKey;
final actions = widget.actions;
final pillColor = widget.pillColor;
final foregroundColor = widget.foregroundColor;
final bottomPadding = widget.bottomPadding;
final leading =
leadingWidget ??
(automaticallyImplyLeading
? impliedSegmentedLeading(context, cupertino)
: null);
final showTitle = title.isNotEmpty || (subtitle ?? '').isNotEmpty;
Widget titlePill(bool expanded) => SegmentedTitlePill(
cupertino: cupertino,
title: title,
subtitle: subtitle,
subtitleIcon: subtitleIcon,
onPressed: widget.expandableTitle ? _toggleTitle : onTitlePressed,
semanticLabel: widget.expandableTitle
? '${titleSemanticLabel ?? title}, ${expanded ? 'expanded' : 'collapsed'}'
: titleSemanticLabel,
buttonKey: expanded ? null : titleKey,
expanded: expanded,
titleAction: expanded ? widget.titleAction : null,
foreground: foregroundColor,
fill: pillColor,
);
final Widget bar = LayoutBuilder(
builder: (context, constraints) => Row(
children: [
if (leading != null) ...[
SegmentedPill(
cupertino: cupertino,
fill: pillColor,
child: leading,
),
const SizedBox(width: 8),
],
Expanded(
// Only as tall as the title: a Material scaffold offers its app
// bar more height than it needs.
child: Align(
alignment: AlignmentDirectional.centerStart,
heightFactor: 1,
child: titleWidget != null
// The main pill fills the row, up to its cap.
? ConstrainedBox(
constraints: BoxConstraints(
maxWidth: titleWidgetMaxWidth,
),
child: SegmentedPill(
cupertino: cupertino,
fill: pillColor,
child: SizedBox(
width: double.infinity,
child: titleWidget,
),
),
)
: showTitle && !widget.expandableTitle
? titlePill(false)
: showTitle
? LayoutBuilder(
builder: (context, titleSpace) => OverlayPortal(
controller: _expandedTitle,
overlayChildBuilder: (context) =>
!(_expanded && widget.expandableTitle)
? const SizedBox.shrink()
: Positioned(
top: 0,
left: 0,
child: CompositedTransformFollower(
link: _titleLink,
showWhenUnlinked: false,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: titleSpace.maxWidth,
),
child: BackdropGroup(
backdropKey: _expandedTitleBackdrop,
child: titlePill(true),
),
),
),
),
child: CompositedTransformTarget(
link: _titleLink,
child: ExcludeSemantics(
excluding: _expanded && widget.expandableTitle,
child: titlePill(false),
),
),
),
)
: const SizedBox.shrink(),
),
),
if (actions.isNotEmpty) ...[
const SizedBox(width: 8),
// The actions keep to the trailing edge at their natural width,
// so a model name shows whole while the title has room; only past
// the title's minimum share does the first action ellipsise.
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: math.max(
0,
constraints.maxWidth -
(leading == null
? 0
: segmentedPieceHeight(cupertino) + 8) -
8 -
constraints.maxWidth * SegmentedBar.minTitleShare,
),
),
child: SegmentedPill(
cupertino: cupertino,
fill: pillColor,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: actions.first),
...actions.skip(1),
],
),
),
),
],
],
),
);
final background = widget._background(context);
final inset = MediaQuery.paddingOf(context).top;
return Stack(
children: [
// The scrim: the page's background, opaque at the edge and fading out
// towards the content, so content scrolled behind the pieces still
// reads. It takes no taps; only the pieces do.
Positioned.fill(
child: IgnorePointer(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
height: inset,
child: ColoredBox(color: background),
),
Expanded(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
background,
background.withValues(alpha: background.a * 0.95),
background.withValues(alpha: 0),
],
stops: const [0, 0.5, 1],
),
),
),
),
],
),
),
),
SafeArea(
bottom: false,
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(
12,
SegmentedBar._topPadding,
12,
bottomPadding,
),
child: MediaQuery.withClampedTextScaling(
maxScaleFactor: SegmentedBar.maxTextScale,
child: BackdropGroup(backdropKey: _piecesBackdrop, child: bar),
),
),
),
],
);
}
}