import 'dart:math' as math; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'floating_bar_layout.dart'; import 'floating_tab_motion.dart'; import 'glass_pill.dart'; /// A tab bar which floats above the bottom edge in a frosted [GlassPill] /// instead of becoming a full-width system bar. Used for the app's /// destinations and for every page's own tabs. /// /// At any width the pill is only as wide as its icon tabs and sits at the /// trailing (right, in left-to-right text) edge, near the thumb, keeping /// [kFloatingBarMargin] from the sides and above the bottom safe area. Only /// the pill takes taps: the space beside it reaches the content behind. /// /// One tinted circle sits behind the selected tab's icon and glides to a /// newly selected tab. At rest it keeps the same gap from its neighbours' slots /// as from the pill's top and bottom, and at the outer tabs the same gap from /// the pill's sides, so the pill's round ends are concentric with it. /// /// The tabs pop in when the bar appears or its set of tabs changes, never /// when only the selection does. /// /// The tabs show icons only. Each tab's label stays its accessible name (and /// the Material tooltip), so screen readers still announce it; the icons must /// be distinct within a bar. /// /// The controls inside remain the platform navigation controls (Material /// [NavigationBar], Cupertino [CupertinoTabBar]), so tab semantics (selected /// state, "tab n of m") come from the host. The Cupertino path builds no /// Material widget. class FloatingDestinationBar extends StatefulWidget { const FloatingDestinationBar({ super.key, required this.cupertino, required this.currentIndex, required this.onTap, required this.items, this.edge = FloatingBarEdge.bottom, }); final bool cupertino; /// The edge the bar floats at. At [FloatingBarEdge.top] (an open item's /// tabs under its pane's top bar) the bar sits at the leading edge, in line /// with the bar's title, and keeps no bottom safe area. final FloatingBarEdge edge; final int currentIndex; final ValueChanged onTap; final List items; /// The icon sizes used by the two host navigation controls. static const double materialIconSize = 28; static const double cupertinoIconSize = 30; /// Padding between each icon and the edge of its selection circle. static const double _materialRing = 8; static const double _cupertinoRing = 6; /// The gap between a circle and the pill's nearest edge or neighbour. /// Keeping these as the source constants makes the bar grow with the icons. static const double _materialEdgeGap = 8; static const double _cupertinoEdgeGap = 6; /// Diameter of the selection circle. static const double materialHighlightSize = materialIconSize + 2 * _materialRing; static const double cupertinoHighlightSize = cupertinoIconSize + 2 * _cupertinoRing; /// Height of the host bar, derived from its circle and the equal edge gaps. static const double materialHeight = materialHighlightSize + 2 * _materialEdgeGap; static const double cupertinoHeight = cupertinoHighlightSize + 2 * _cupertinoEdgeGap; /// The gap between a tab's circle and the pill's top and bottom; the outer /// circles keep the same gap from the pill's sides, and neighbours from /// each other. static const double materialEdgeGap = _materialEdgeGap; static const double cupertinoEdgeGap = _cupertinoEdgeGap; /// The additional breathing room between neighbouring selection circles. static const double materialNeighbourGap = 15; static const double cupertinoNeighbourGap = 13; /// Width of one equal native tab slot at the requested neighbour spacing. static const double materialTabWidth = materialHighlightSize + materialNeighbourGap; static const double cupertinoTabWidth = cupertinoHighlightSize + cupertinoNeighbourGap; /// The side margin at [FloatingBarEdge.top], matching the top bar's own. static const double topMargin = 12; /// The selection highlight inside each bar, for tests. static const Key highlightKey = ValueKey( 'floating-destination-bar.highlight', ); /// The width of a pill holding [tabs] tabs, when the space allows it. static double pillWidth({required bool cupertino, required int tabs}) => cupertino ? cupertinoHighlightSize * tabs + 2 * cupertinoEdgeGap + math.max(0, tabs - 1) * cupertinoNeighbourGap : materialHighlightSize * tabs + 2 * materialEdgeGap + math.max(0, tabs - 1) * materialNeighbourGap; @override State createState() => _FloatingDestinationBarState(); } class _FloatingDestinationBarState extends State with TickerProviderStateMixin { late final FloatingTabMotion _motion = FloatingTabMotion(this); bool _entered = false; bool get cupertino => widget.cupertino; List get items => widget.items; int get currentIndex => widget.currentIndex; @override void didChangeDependencies() { super.didChangeDependencies(); if (_entered) return; _entered = true; _motion.enter(context, count: items.length, selected: currentIndex); } @override void didUpdateWidget(FloatingDestinationBar oldWidget) { super.didUpdateWidget(oldWidget); if (_tabSetIdentity(oldWidget.items) != _tabSetIdentity(items)) { // New tabs (a run's page tabs appearing): they pop in, and the // highlight starts on the selected one. _motion.enter(context, count: items.length, selected: currentIndex); } else if (oldWidget.currentIndex != currentIndex) { _motion.select(context, currentIndex); } } @override void dispose() { _motion.dispose(); super.dispose(); } static String _tabSetIdentity(List items) => items.map((item) => '${item.key ?? item.label}:${item.label}').join('|'); @override Widget build(BuildContext context) { final top = widget.edge == FloatingBarEdge.top; final bar = LayoutBuilder( builder: (context, constraints) { final width = math.max(0.0, math.min(constraints.maxWidth, _tabsWidth)); return Align( // As tall as the pill, so a scaffold or overlay measures the bar // and not the whole area it may grow into. heightFactor: 1, alignment: top ? AlignmentDirectional.topStart : AlignmentDirectional.bottomEnd, child: SizedBox( width: width, // The insets are handled around the pill. The host bars pad // themselves by any media padding left over (a page's top bar, // another floating bar below a pane), which would swell the pill. child: MediaQuery.removePadding( context: context, removeTop: true, removeBottom: true, removeLeft: true, removeRight: true, child: GlassPill( cupertino: cupertino, child: _edgeAligned( context, width, cupertino ? _cupertinoBar(context, _slot(width)) : _materialBar(context), ), ), ), ), ); }, ); if (top) { // Under a top bar: no safe area to keep clear of, only the gap to the // content below. return Padding( padding: const EdgeInsets.fromLTRB( FloatingDestinationBar.topMargin, 0, FloatingDestinationBar.topMargin, 8, ), child: bar, ); } return SafeArea( top: false, minimum: const EdgeInsets.fromLTRB( kFloatingBarMargin, 0, kFloatingBarMargin, kFloatingBarMargin, ), child: bar, ); } double get _highlight => cupertino ? FloatingDestinationBar.cupertinoHighlightSize : FloatingDestinationBar.materialHighlightSize; double get _gap => cupertino ? FloatingDestinationBar.cupertinoEdgeGap : FloatingDestinationBar.materialEdgeGap; double get _neighbourGap => cupertino ? FloatingDestinationBar.cupertinoNeighbourGap : FloatingDestinationBar.materialNeighbourGap; /// The width the icon-only tabs need side by side. Icons do not scale with /// text, so the pill keeps its size at any text scale. double get _tabsWidth => FloatingDestinationBar.pillWidth( cupertino: cupertino, tabs: items.length, ); /// The gap between neighbouring circles in a pill [width] wide: the named /// one, or less in a pill squeezed below its tabs' width. double _neighbour(double width) { final count = items.length; if (count < 2) return _neighbourGap; final available = math.max(0.0, width - 2 * _gap - count * _highlight); return math.min(_neighbourGap, available / (count - 1)); } /// The width of each equal tab slot, which is also the distance between /// neighbouring circles' centres. double _slot(double width) => _highlight + math.max(0, _neighbour(width)); bool get _hasSelection => currentIndex >= 0 && currentIndex < items.length; /// Insets the host bar's equal tab slots so the outer circles sit the edge /// gap from the pill's sides. A pill squeezed below its tabs' width keeps /// that gap and narrows the gaps between neighbours instead, as long as /// the circles still fit side by side. The Material highlight is laid over /// the first slot, behind the host bar. Widget _edgeAligned(BuildContext context, double width, Widget bar) { final count = items.length; if (count == 0) return bar; // The native bars use equal-width slots. Let their slot centers be the // desired circle centers, and translate the slots by half the difference // between the outer and neighbour gaps. The pill clips the harmless // overflow of the native slot backgrounds, while the circles remain // exactly edge-aligned. final slot = _slot(width); final offset = _gap - _neighbour(width) / 2; return ClipRect( child: SizedBox( width: width, height: cupertino ? FloatingDestinationBar.cupertinoHeight : FloatingDestinationBar.materialHeight, child: OverflowBox( alignment: AlignmentDirectional.topStart, minWidth: 0, maxWidth: double.infinity, child: Transform.translate( offset: Offset(offset, 0), child: SizedBox( width: slot * count, child: Stack( fit: StackFit.expand, children: [ if (!cupertino && _hasSelection) PositionedDirectional( start: 0, top: 0, bottom: 0, width: slot, child: _highlightFor(context, slot), ), bar, ], ), ), ), ), ), ); } /// The bar's one selection highlight, laid out over tab 0. Widget _highlightFor(BuildContext context, double slot) => FloatingTabHighlight( key: FloatingDestinationBar.highlightKey, motion: _motion, slot: slot, size: _highlight, color: cupertino ? CupertinoTheme.of(context).primaryColor.withValues(alpha: 0.16) : Theme.of(context).colorScheme.secondaryContainer, ); Widget _materialBar(BuildContext context) { return NavigationBarTheme( data: const NavigationBarThemeData( backgroundColor: Colors.transparent, elevation: 0, surfaceTintColor: Colors.transparent, // The bar draws one gliding highlight behind the icons (the stock // indicator is a fixed 64x32 that jumps); the stock one stays for // its circular ink response. indicatorColor: Colors.transparent, indicatorShape: CircleBorder(), height: FloatingDestinationBar.materialHeight, iconTheme: WidgetStatePropertyAll( IconThemeData(size: FloatingDestinationBar.materialIconSize), ), // Icons only; the label remains each tab's accessible name and its // tooltip. labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, ), child: NavigationBar( selectedIndex: currentIndex, onDestinationSelected: widget.onTap, destinations: [ for (var index = 0; index < items.length; index += 1) NavigationDestination( key: items[index].key, icon: _icon(items[index].icon, index), selectedIcon: _icon( items[index].selectedIcon ?? items[index].icon, index, ), label: items[index].label, ), ], ), ); } /// The stock Cupertino bar, transparent inside the pill. Each tab shows its /// icon only, named by its label for accessibility; the item's key covers /// the whole tab, and the highlight behind the selected icon makes the /// selection read at a glance, not by colour alone. /// /// The host blurs whatever is behind its translucent background, so the /// highlight is painted from inside tab 0, under the icons but above the /// blur. Widget _cupertinoBar(BuildContext context, double slot) { Widget tab( FloatingDestinationItem item, { required bool selected, required int index, }) { final icon = _icon( selected ? item.selectedIcon ?? item.icon : item.icon, index, ); return KeyedSubtree( key: item.key, child: Semantics( label: item.label, // The host centres the icon above a 4px bottom inset; 4 above it // centres the icon and its highlight in the whole bar, so the // highlight is as far from the pill's top as from its bottom. child: Padding( padding: const EdgeInsets.only(top: 4), child: index == 0 && _hasSelection ? Stack( clipBehavior: Clip.none, alignment: Alignment.center, children: [ Positioned.fill(child: _highlightFor(context, slot)), icon, ], ) : icon, ), ), ); } // The tab bar does not scale its text on iOS either; its height is fixed. return MediaQuery.withNoTextScaling( child: CupertinoTabBar( backgroundColor: CupertinoColors.transparent, border: null, // Secondary-label translucency over glass falls below text contrast // requirements. The host label role remains readable in both themes. inactiveColor: CupertinoColors.label.resolveFrom(context), iconSize: FloatingDestinationBar.cupertinoIconSize, height: FloatingDestinationBar.cupertinoHeight, currentIndex: currentIndex, onTap: widget.onTap, items: [ for (var index = 0; index < items.length; index += 1) BottomNavigationBarItem( icon: tab(items[index], selected: false, index: index), activeIcon: tab(items[index], selected: true, index: index), ), ], ), ); } /// Tab [index]'s icon, animated by the bar: the host swaps a tab's icon /// subtree on selection, so the icon itself holds no animation state. Widget _icon(Widget child, int index) => FloatingTabEntrance(motion: _motion, index: index, child: child); } /// The platform-neutral data needed by [FloatingDestinationBar]. class FloatingDestinationItem { const FloatingDestinationItem({ required this.icon, required this.label, this.selectedIcon, this.key, }); final Widget icon; /// The tab's accessible name (and Material tooltip); not drawn. final String label; final Widget? selectedIcon; /// Identifies the whole tab, for tests and automation. final Key? key; }