Grow the tapped chat row into the chat page on phones

Replace the identity-avatar Hero with a container transform: the row's
surface, tint and edge marker morph into the full page while the content
cross-fades, and Back, the Cupertino edge swipe or Android predictive back
shrink the page into the open chat's row. Reduced motion or a row off
screen fades instead; wide layouts are unchanged.
This commit is contained in:
2026-11-10 03:11:05 +00:00
parent 60b4c495f1
commit eea1361980
16 changed files with 1392 additions and 124 deletions
@@ -34,7 +34,6 @@ class ChatThreadHeader extends StatelessWidget {
this.moreActions = const [],
this.chatColor,
this.identity,
this.identityHeroTag,
});
final String title;
@@ -55,9 +54,8 @@ class ChatThreadHeader extends StatelessWidget {
/// The chat's colour name, or null for none.
final String? chatColor;
/// The chat identity carried from the mobile session row into this header.
/// The chat's identity avatar, shown in the title on a phone.
final Widget? identity;
final String? identityHeroTag;
@override
Widget build(BuildContext context) {
@@ -68,12 +66,6 @@ class ChatThreadHeader extends StatelessWidget {
builder: (context, constraints) {
final textScale = MediaQuery.textScalerOf(context).scale(14) / 14;
final compact = constraints.maxWidth / textScale < 800;
final heroIdentity =
identity == null ||
identityHeroTag == null ||
(MediaQuery.maybeDisableAnimationsOf(context) ?? false)
? identity
: Hero(tag: identityHeroTag!, child: identity!);
final Widget bar = SegmentedBar(
cupertino: cupertino,
pillColor: tint?.fill,
@@ -89,7 +81,7 @@ class ChatThreadHeader extends StatelessWidget {
)
: null,
title: title.isEmpty ? 'Chat' : title,
titleLeading: heroIdentity,
titleLeading: identity,
subtitle: ServerContext.metadata(context, folder),
subtitleIcon: cupertino
? CupertinoIcons.folder
@@ -1393,13 +1393,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
MediaQuery.sizeOf(context).width >= kListDetailMinWidth
? null
: ChatSessionAvatar(session: session, selected: true),
identityHeroTag:
widget.useNativeBack &&
session != null &&
MediaQuery.sizeOf(context).width < kListDetailMinWidth &&
!(MediaQuery.maybeDisableAnimationsOf(context) ?? false)
? 'chat-identity-${widget.sessionId}'
: null,
onInfo: _openInfo,
showBack: canGoBack,
// A pushed page keeps the platform's stock Back (pop this route); a
+14 -1
View File
@@ -10,6 +10,7 @@ import '../../shell/empty_detail_pane.dart';
import '../../shell/list_detail.dart';
import 'dart:async';
import '../../ui/motion/motion.dart';
import '../../ui/motion/container_transform_source.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show setEquals;
@@ -415,6 +416,13 @@ class _ChatScreenState extends State<ChatScreen>
/// On a phone the open chat is a real page above the main screen.
final DetailPageHost _page = DetailPageHost();
/// The list rows the phone's chat page grows from and shrinks back into:
/// the open chat's row, also after the page switched to another chat.
final ContainerTransformSources _rowSources = ContainerTransformSources();
late final ContainerTransformLink _growFromRow = _rowSources.link(
() => _selected,
);
@override
bool get _pageOpen => _page.open;
@@ -550,13 +558,14 @@ class _ChatScreenState extends State<ChatScreen>
selected: selected != null && !beside && !_usedWorkspace,
destination: AppDestination.chat,
onClosed: _back,
growFrom: _growFromRow,
builder: (context) => selected == null
? const SizedBox.shrink()
: ShellBar(barless: true, child: _workspaceView()),
);
// The session list pads its first row by the bar's height itself, so it
// scrolls behind the shell's floating bar like the other lists.
final fullList = ChatSessionsScreen(
final sessions = ChatSessionsScreen(
gateway: widget.gateway,
embedded: true,
syncToken: widget.syncToken,
@@ -575,6 +584,10 @@ class _ChatScreenState extends State<ChatScreen>
_sidebarMode == ChatSidebarMode.expanded) &&
(beside || !_usedWorkspace || selected == null),
);
final fullList = ContainerTransformScope(
sources: _rowSources,
child: sessions,
);
final list = _sidebarList(fullList, selected, beside);
if (!beside) {
if (!_usedWorkspace) return list;
@@ -6,7 +6,7 @@ import '../../../../core/api_gateway.dart';
import '../../../../ui/layout/app_list_avatar.dart';
import '../../../../ui/layout/app_list_row.dart';
import '../../../../ui/text/relative_time_label.dart';
import '../../../../shell/list_detail_policy.dart';
import '../../../../ui/motion/container_transform_source.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
@@ -65,11 +65,34 @@ class ChatSessionRow extends StatelessWidget {
final id = '${session['id'] ?? ''}';
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final closed = chatSessionRowStatus(session, unseen: false) == 'Closed';
final unread = unseen && !closed;
final accent = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final shade = chatColorShade(context, chatSessionColor(session));
final marker = shade ?? accent;
final tint = AppListRow.tintFor(context, shade, cupertino: cupertino);
final background = cupertino
? CupertinoDynamicColor.resolve(
CupertinoTheme.of(context).scaffoldBackgroundColor,
context,
)
: Theme.of(context).scaffoldBackgroundColor;
// On a phone the chat's page grows out of this row and shrinks back
// into it; the surface it starts from is the row's tint over the list.
return ContainerTransformSource(
id: id,
color: tint == null ? background : Color.alphaBlend(tint, background),
marker: marker,
markerWidth: visible ? (selected ? 10 : 3) : 0,
child: _marked(context, id, marker, accent),
);
}
Widget _marked(BuildContext context, String id, Color marker, Color accent) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final closed = chatSessionRowStatus(session, unseen: false) == 'Closed';
final unread = unseen && !closed;
final text = chatSessionSubtitle(session);
final updatedAt = _chatSessionInstant(session['updated_at']);
final avatar = ChatSessionAvatar(
@@ -80,15 +103,9 @@ class ChatSessionRow extends StatelessWidget {
: chatSessionBackgroundTasks(session),
selected: selected,
);
final mobileHero =
!showsListBesideDetail(context) &&
!(MediaQuery.maybeDisableAnimationsOf(context) ?? false);
final identity = mobileHero
? Hero(tag: 'chat-identity-$id', child: avatar)
: avatar;
return ChatVisibilityMarker(
sessionId: id,
color: chatColorShade(context, chatSessionColor(session)) ?? accent,
color: marker,
visible: visible,
active: selected,
child: AppListRow(
@@ -102,7 +119,7 @@ class ChatSessionRow extends StatelessWidget {
onLongPress: selectionOnly ? null : onLongPress,
accent: chatColorShade(context, chatSessionColor(session)),
showAccentBorder: false,
leading: identity,
leading: avatar,
// The star rides in the title's own text, so a narrow row ellipsises
// them together.
title: Text.rich(
@@ -65,8 +65,8 @@ class _ChatWorkspaceEntranceState extends State<ChatWorkspaceEntrance>
@override
Widget build(BuildContext context) {
final content = HeroMode(
// The initial pushed page has a native Hero. Here both surfaces share
// one route; only the workspace entrance animates, never duplicate tags.
// Both surfaces share one route here; only the workspace entrance
// animates, so no Hero inside the chat flies or duplicates a tag.
enabled: false,
child: TickerMode(enabled: widget.visible, child: widget.child),
);
+18 -1
View File
@@ -3,6 +3,8 @@ import 'package:flutter/material.dart';
import '../ui/adaptive/host.dart';
import '../ui/adaptive/segmented_bar.dart';
import '../ui/motion/container_transform_route.dart';
import '../ui/motion/container_transform_source.dart';
import 'destination.dart';
import 'shell_bar.dart';
@@ -26,6 +28,7 @@ class DetailPageHost {
required AppDestination destination,
required WidgetBuilder builder,
required VoidCallback onClosed,
ContainerTransformLink? growFrom,
}) {
if (selected && _route != null) {
// Another route cannot be rebuilt mid-build; the page follows next frame.
@@ -38,6 +41,7 @@ class DetailPageHost {
final route = detailPageRoute(
context,
destination: destination,
growFrom: growFrom,
builder: (context) => ValueListenableBuilder<WidgetBuilder?>(
valueListenable: _content,
builder: (context, build, _) =>
@@ -78,13 +82,26 @@ class DetailPageHost {
/// A full-screen page whose bar shows what the page's content publishes
/// through [ShellBar] (title and actions), with the platform's Back.
///
/// With [growFrom] the page grows out of the list item that opened it and
/// shrinks back into it ([ContainerTransformPageRoute]); otherwise it enters
/// with the platform's page transition.
PageRoute<void> detailPageRoute(
BuildContext context, {
required AppDestination destination,
required WidgetBuilder builder,
ContainerTransformLink? growFrom,
}) {
final page = DetailPane(destination: destination, builder: builder);
return usesCupertinoHost(context)
final cupertino = usesCupertinoHost(context);
if (growFrom != null) {
return ContainerTransformPageRoute<void>(
link: growFrom,
cupertino: cupertino,
builder: (_) => page,
);
}
return cupertino
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(builder: (_) => page);
}
+9 -3
View File
@@ -118,6 +118,14 @@ class AppListRow extends StatelessWidget {
/// Overrides the host detection (some features pick a style per platform).
final bool? cupertino;
/// The faint tint an unselected row with [accent] wears over the list.
static Color? tintFor(
BuildContext context,
Color? accent, {
required bool cupertino,
}) =>
accent?.withValues(alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07);
/// The open row's fill on each host.
static Color selectedColor(BuildContext context, {required bool cupertino}) =>
cupertino
@@ -173,9 +181,7 @@ class AppListRow extends StatelessWidget {
],
),
);
final tint = accent?.withValues(
alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07,
);
final tint = tintFor(context, accent, cupertino: cupertino);
final surface = cupertino
? _CupertinoRowSurface(
tapKey: tapKey,
@@ -0,0 +1,264 @@
import 'package:flutter/widgets.dart';
import 'container_transform_source.dart';
import 'motion.dart';
/// Key of the growing surface, for finders.
const containerTransformSurfaceKey = ValueKey<String>(
'container-transform-surface',
);
/// A page growing out of its item's rectangle and shrinking back into it.
///
/// The surface morphs from the item's (its bounds, shape, tint and edge
/// marker) to the page's while the content cross-fades: on opening the item
/// is covered early and the page appears late; on closing the page goes
/// early and the item shows through late. The list behind never moves.
///
/// Without an [origin] (reduced motion, or the item is not on screen) the
/// page simply fades. The widget tree is the same in every state, so the
/// page keeps its state at rest and through any transition.
class ContainerTransformFlight extends StatefulWidget {
const ContainerTransformFlight({
super.key,
required this.animation,
required this.origin,
required this.closing,
required this.tracking,
required this.pageColor,
required this.scrimColor,
required this.child,
});
/// The route's animation: 0 at the item, 1 as the full page.
final Animation<double> animation;
/// Resolves where to grow from or shrink into; null fades instead.
final ContainerTransformOrigin? Function()? origin;
/// Whether the page is on its way back into the item.
final bool Function() closing;
/// Whether a finger drives the animation (it then follows linearly).
final bool Function() tracking;
final Color pageColor;
final Color scrimColor;
final Widget child;
@override
State<ContainerTransformFlight> createState() =>
_ContainerTransformFlightState();
}
class _ContainerTransformFlightState extends State<ContainerTransformFlight> {
ContainerTransformOrigin? _origin;
bool _resolved = false;
@override
void initState() {
super.initState();
widget.animation.addStatusListener(_statusChanged);
}
@override
void didUpdateWidget(ContainerTransformFlight oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.animation != widget.animation) {
oldWidget.animation.removeStatusListener(_statusChanged);
widget.animation.addStatusListener(_statusChanged);
}
}
@override
void dispose() {
widget.animation.removeStatusListener(_statusChanged);
super.dispose();
}
// Each flight measures its item afresh: the open item may have changed,
// or the window may have resized, while the page was up.
void _statusChanged(AnimationStatus status) {
if (status.isCompleted || status.isDismissed) _resolved = false;
}
ContainerTransformOrigin? _resolve() {
if (!_resolved) {
_resolved = true;
_origin = widget.origin?.call();
}
return _origin;
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final size = constraints.biggest;
return AnimatedBuilder(
animation: widget.animation,
child: widget.child,
builder: (context, child) {
final t = widget.animation.value;
final atRest = widget.animation.isCompleted;
final origin = atRest ? null : _resolve();
final frame = origin == null
? _Frame.fade(t, size, widget.pageColor)
: _Frame.transform(
t,
_local(origin.rect),
size,
origin,
widget.pageColor,
closing: widget.closing(),
tracking: widget.tracking(),
);
// The list dims as the page grows and brightens as it shrinks.
final scrim = atRest ? 0.0 : Motion.containerTransformScrim * t;
return Stack(
fit: StackFit.expand,
children: [
IgnorePointer(
child: ColoredBox(
color: widget.scrimColor.withValues(
alpha: widget.scrimColor.a * scrim,
),
),
),
Positioned.fromRect(
rect: frame.rect,
child: Opacity(
opacity: frame.surfaceOpacity,
child: ClipRRect(
key: containerTransformSurfaceKey,
borderRadius: frame.radius,
clipBehavior: atRest ? Clip.none : Clip.hardEdge,
child: DecoratedBox(
decoration: BoxDecoration(color: frame.color),
position: DecorationPosition.background,
child: _Content(
size: size,
opacity: frame.contentOpacity,
marker: frame.marker,
markerWidth: frame.markerWidth,
child: child!,
),
),
),
),
),
],
);
},
);
},
);
/// [global] in this page's coordinates; the page fills its navigator.
Rect _local(Rect global) {
final box = context.findRenderObject();
if (box is! RenderBox || !box.hasSize) return global;
return global.shift(-box.localToGlobal(Offset.zero));
}
}
/// The page laid out at its full size, aligned to the top of the surface
/// and scaled to its width, so nothing inside relayouts as it grows.
class _Content extends StatelessWidget {
const _Content({
required this.size,
required this.opacity,
required this.marker,
required this.markerWidth,
required this.child,
});
final Size size;
final double opacity;
final Color? marker;
final double markerWidth;
final Widget child;
@override
Widget build(BuildContext context) => DecoratedBox(
position: DecorationPosition.foreground,
decoration: BoxDecoration(
border: marker == null || markerWidth <= 0
? null
: BorderDirectional(
start: BorderSide(color: marker!, width: markerWidth),
),
),
child: FittedBox(
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
clipBehavior: Clip.none,
child: SizedBox.fromSize(
size: size,
child: Opacity(opacity: opacity, child: child),
),
),
);
}
class _Frame {
const _Frame({
required this.rect,
required this.radius,
required this.color,
required this.surfaceOpacity,
required this.contentOpacity,
this.marker,
this.markerWidth = 0,
});
/// The whole page fading in place.
factory _Frame.fade(double t, Size size, Color pageColor) => _Frame(
rect: Offset.zero & size,
radius: BorderRadius.zero,
color: pageColor,
surfaceOpacity: Curves.easeInOut.transform(t),
contentOpacity: 1,
);
factory _Frame.transform(
double t,
Rect start,
Size size,
ContainerTransformOrigin origin,
Color pageColor, {
required bool closing,
required bool tracking,
}) {
const curve = Curves.fastOutSlowIn;
// Played backwards in time, the same easing reads as the item settling.
final grown = tracking
? t
: closing
? curve.flipped.transform(t)
: curve.transform(t);
// Opening covers the item first and shows the page late; closing hides
// the page first and uncovers the item late.
final surface = closing
? const Interval(0, 0.3).transform(t)
: const Interval(0, 0.2).transform(t);
final content = closing
? const Interval(0.7, 1).transform(t)
: const Interval(0.25, 0.7, curve: Curves.easeIn).transform(t);
return _Frame(
rect: Rect.lerp(start, Offset.zero & size, grown)!,
radius: BorderRadius.lerp(origin.borderRadius, BorderRadius.zero, grown)!,
color: Color.lerp(origin.color, pageColor, grown)!,
surfaceOpacity: surface,
contentOpacity: content,
marker: origin.marker,
markerWidth: origin.markerWidth * (1 - grown),
);
}
final Rect rect;
final BorderRadius radius;
final Color color;
final double surfaceOpacity;
final double contentOpacity;
final Color? marker;
final double markerWidth;
}
@@ -0,0 +1,181 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
/// What a back gesture needs from the page it closes.
abstract interface class ContainerTransformGestureRoute
implements PredictiveBackRoute {
/// Whether a back gesture may start now: the page is current, at rest and
/// would really pop.
bool get backGestureEnabled;
/// A finger took the page from the start edge.
void startSwipeBack();
/// The finger moved by [fraction] of the page's width toward the end edge.
void updateSwipeBack(double fraction);
/// The finger let go at [velocity] page widths per second.
void endSwipeBack(double velocity);
}
/// The back gestures of a page that shrinks into its item: on a Cupertino
/// host the native swipe from the start edge; on Android the system's
/// predictive back. Either one drives the page's own animation, so the
/// shrink follows the finger, and releasing commits or cancels it.
class ContainerTransformBackGestures extends StatelessWidget {
const ContainerTransformBackGestures({
super.key,
required this.route,
required this.cupertino,
required this.child,
});
final ContainerTransformGestureRoute route;
final bool cupertino;
final Widget child;
@override
Widget build(BuildContext context) => cupertino
? _EdgeSwipeBack(route: route, child: child)
: _PredictiveBack(route: route, child: child);
}
/// The width of the start edge that takes a swipe back, as in iOS.
const double _edgeWidth = 20;
class _EdgeSwipeBack extends StatefulWidget {
const _EdgeSwipeBack({required this.route, required this.child});
final ContainerTransformGestureRoute route;
final Widget child;
@override
State<_EdgeSwipeBack> createState() => _EdgeSwipeBackState();
}
class _EdgeSwipeBackState extends State<_EdgeSwipeBack> {
late final HorizontalDragGestureRecognizer _recognizer =
HorizontalDragGestureRecognizer(debugOwner: this)
..onStart = _start
..onUpdate = _update
..onEnd = _end
..onCancel = _cancel;
bool _dragging = false;
@override
void dispose() {
_recognizer.dispose();
if (_dragging) widget.route.endSwipeBack(0);
super.dispose();
}
double _logical(double value) =>
Directionality.of(context) == TextDirection.rtl ? -value : value;
void _start(DragStartDetails details) {
_dragging = true;
widget.route.startSwipeBack();
}
void _update(DragUpdateDetails details) {
if (!_dragging) return;
widget.route.updateSwipeBack(
_logical(details.primaryDelta! / context.size!.width),
);
}
void _end(DragEndDetails details) {
if (!_dragging) return;
_dragging = false;
widget.route.endSwipeBack(
_logical(details.velocity.pixelsPerSecond.dx / context.size!.width),
);
}
void _cancel() {
if (!_dragging) return;
_dragging = false;
widget.route.endSwipeBack(0);
}
@override
Widget build(BuildContext context) {
final padding = MediaQuery.paddingOf(context);
final notch = Directionality.of(context) == TextDirection.rtl
? padding.right
: padding.left;
return Stack(
fit: StackFit.passthrough,
children: [
widget.child,
PositionedDirectional(
start: 0,
top: 0,
bottom: 0,
width: math.max(notch, _edgeWidth),
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (event) {
if (widget.route.backGestureEnabled) {
_recognizer.addPointer(event);
}
},
),
),
],
);
}
}
/// Forwards Android's predictive back to the page, as the stock Material
/// page transition does, without that transition's own shrink.
class _PredictiveBack extends StatefulWidget {
const _PredictiveBack({required this.route, required this.child});
final ContainerTransformGestureRoute route;
final Widget child;
@override
State<_PredictiveBack> createState() => _PredictiveBackState();
}
class _PredictiveBackState extends State<_PredictiveBack>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
bool handleStartBackGesture(PredictiveBackEvent backEvent) {
if (backEvent.isButtonEvent || !widget.route.backGestureEnabled) {
return false;
}
widget.route.handleStartBackGesture(progress: 1 - backEvent.progress);
return true;
}
@override
void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) => widget
.route
.handleUpdateBackGestureProgress(progress: 1 - backEvent.progress);
@override
void handleCancelBackGesture() => widget.route.handleCancelBackGesture();
@override
void handleCommitBackGesture() => widget.route.handleCommitBackGesture();
@override
Widget build(BuildContext context) => widget.child;
}
@@ -0,0 +1,173 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'container_transform_flight.dart';
import 'container_transform_gestures.dart';
import 'container_transform_source.dart';
import 'motion.dart';
/// How long a page released mid-swipe takes to settle, as in iOS.
const Duration _droppedSwipeDuration = Duration(milliseconds: 350);
/// A full-screen page that grows out of the item that opened it and shrinks
/// back into it on Back (Material's container transform).
///
/// [link] resolves the item each time the page animates, so closing after
/// another item took the page shrinks into that one. When the item is not on
/// screen, or the system asks for reduced motion, the page fades instead.
/// The list behind stays put. A Cupertino host keeps the native swipe back
/// from the start edge and Android its predictive back; both drive the
/// shrink with the finger. The animation-speed setting scales every
/// duration through the scheduler clock.
class ContainerTransformPageRoute<T> extends PageRoute<T>
implements ContainerTransformGestureRoute {
ContainerTransformPageRoute({
required this.builder,
required this.link,
required this.cupertino,
super.settings,
});
final WidgetBuilder builder;
final ContainerTransformLink link;
final bool cupertino;
bool get _reducedMotion {
final context = navigator?.context;
return context != null &&
(MediaQuery.maybeDisableAnimationsOf(context) ?? false);
}
@override
Duration get transitionDuration =>
_reducedMotion ? Motion.quick : Motion.containerTransform;
@override
Duration get reverseTransitionDuration =>
_reducedMotion ? Motion.quick : Motion.containerTransformReverse;
@override
bool get opaque => true;
@override
bool get maintainState => true;
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
/// The list this page grew from never moves under it.
@override
bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) => false;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) => Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: builder(context),
);
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
final pageColor = cupertino
? CupertinoDynamicColor.resolve(
CupertinoTheme.of(context).scaffoldBackgroundColor,
context,
)
: Theme.of(context).scaffoldBackgroundColor;
Widget page = ContainerTransformFlight(
animation: animation,
origin: reduced ? null : link.resolve,
closing: () =>
animation.status == AnimationStatus.reverse || popGestureInProgress,
tracking: () => popGestureInProgress,
pageColor: pageColor,
scrimColor: cupertino
? CupertinoColors.black
: Theme.of(context).colorScheme.scrim,
child: child,
);
if (cupertino) {
// A page pushed over this one keeps the native parallax.
page = CupertinoPageTransition(
primaryRouteAnimation: kAlwaysCompleteAnimation,
secondaryRouteAnimation: secondaryAnimation,
linearTransition: popGestureInProgress,
child: page,
);
}
return ContainerTransformBackGestures(
route: this,
cupertino: cupertino,
child: page,
);
}
@override
bool get backGestureEnabled =>
isCurrent &&
popGestureEnabled &&
!(navigator?.userGestureInProgress ?? true);
@override
void startSwipeBack() => navigator?.didStartUserGesture();
@override
void updateSwipeBack(double fraction) {
if (!isCurrent) return;
controller?.value -= fraction;
}
@override
void endSwipeBack(double velocity) {
final controller = this.controller;
final navigator = this.navigator;
if (controller == null || navigator == null) return;
// As in iOS: a fling decides; otherwise the page goes back past halfway.
final bool stay;
if (!isCurrent) {
stay = isActive;
} else if (velocity.abs() >= 1) {
stay = velocity <= 0;
} else {
stay = controller.value > 0.5;
}
const curve = Curves.fastEaseInToSlowEaseOut;
if (stay) {
controller.animateTo(1, duration: _droppedSwipeDuration, curve: curve);
} else {
if (isCurrent) navigator.pop();
if (controller.isAnimating) {
controller.animateBack(
0,
duration: _droppedSwipeDuration,
curve: curve,
);
}
}
if (!controller.isAnimating) {
navigator.didStopUserGesture();
return;
}
// The gesture lasts until the page settles, so the shrink keeps
// following linearly instead of jumping onto the eased curve.
late final AnimationStatusListener settle;
settle = (_) {
navigator.didStopUserGesture();
controller.removeStatusListener(settle);
};
controller.addStatusListener(settle);
}
}
@@ -0,0 +1,145 @@
import 'package:flutter/widgets.dart';
/// Where a container transform starts and ends: an item's rectangle on the
/// screen and the surface it wears there.
@immutable
class ContainerTransformOrigin {
const ContainerTransformOrigin({
required this.rect,
required this.color,
this.borderRadius = BorderRadius.zero,
this.marker,
this.markerWidth = 0,
});
/// The item's bounds in global coordinates.
final Rect rect;
/// The item's opaque surface (its tint over the list's background).
final Color color;
final BorderRadius borderRadius;
/// The colour of the item's leading-edge marker, if it shows one.
final Color? marker;
final double markerWidth;
}
/// The items of one list that pages can grow from, by key.
class ContainerTransformSources {
final Map<Object, _ContainerTransformSourceState> _sources = {};
/// [key]'s current place and surface, or null when it is not laid out
/// (scrolled away, not built yet, or its list is gone).
ContainerTransformOrigin? originOf(Object? key) {
if (key == null) return null;
return _sources[key]?._origin();
}
/// A link a route can resolve [key] through each time it animates.
ContainerTransformLink link(Object? Function() key) =>
ContainerTransformLink(() => originOf(key()));
}
/// Resolves a route's origin lazily: the open item can change while the page
/// is up (another chat switched in), and closing shrinks into that one.
class ContainerTransformLink {
const ContainerTransformLink(this.resolve);
final ContainerTransformOrigin? Function() resolve;
}
/// Offers [ContainerTransformSources] to the items below it.
class ContainerTransformScope extends InheritedWidget {
const ContainerTransformScope({
super.key,
required this.sources,
required super.child,
});
final ContainerTransformSources sources;
static ContainerTransformSources? maybeOf(BuildContext context) =>
context.getInheritedWidgetOfExactType<ContainerTransformScope>()?.sources;
@override
bool updateShouldNotify(ContainerTransformScope oldWidget) =>
sources != oldWidget.sources;
}
/// Registers [child] as the item [id] a page can grow from and shrink into.
/// Without a [ContainerTransformScope] above it, it only builds [child].
class ContainerTransformSource extends StatefulWidget {
const ContainerTransformSource({
super.key,
required this.id,
required this.color,
this.borderRadius = BorderRadius.zero,
this.marker,
this.markerWidth = 0,
required this.child,
});
final Object id;
final Color color;
final BorderRadius borderRadius;
final Color? marker;
final double markerWidth;
final Widget child;
@override
State<ContainerTransformSource> createState() =>
_ContainerTransformSourceState();
}
class _ContainerTransformSourceState extends State<ContainerTransformSource> {
ContainerTransformSources? _sources;
Object? _id;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_register();
}
@override
void didUpdateWidget(ContainerTransformSource oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.id != widget.id) _register();
}
void _register() {
_unregister();
final sources = ContainerTransformScope.maybeOf(context);
_sources = sources;
_id = widget.id;
sources?._sources[widget.id] = this;
}
void _unregister() {
final sources = _sources;
if (sources != null && sources._sources[_id] == this) {
sources._sources.remove(_id);
}
}
ContainerTransformOrigin? _origin() {
final box = context.findRenderObject();
if (box is! RenderBox || !box.attached || !box.hasSize) return null;
return ContainerTransformOrigin(
rect: box.localToGlobal(Offset.zero) & box.size,
color: widget.color,
borderRadius: widget.borderRadius,
marker: widget.marker,
markerWidth: widget.markerWidth,
);
}
@override
void dispose() {
_unregister();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
+9
View File
@@ -95,6 +95,15 @@ abstract final class Motion {
/// softly with no overshoot.
static const Curve sentMessageCurve = Cubic(0.05, 0.7, 0.1, 1);
/// A tapped item growing into its page (Material's container transform).
static const Duration containerTransform = Duration(milliseconds: 300);
/// The page shrinking back into its item.
static const Duration containerTransformReverse = Duration(milliseconds: 250);
/// How far the list behind a growing page dims, at most.
static const double containerTransformScrim = 0.2;
static const Curve curve = Curves.easeOutCubic;
/// [duration], or zero under the system's reduce-motion setting.