flutter / flutter

Flutter makes it easy and fast to build beautiful apps for mobile and beyond
https://flutter.dev
BSD 3-Clause "New" or "Revised" License
165.08k stars 27.21k forks source link

[flutter_adaptive_scaffold] Inconsistent theming on NavigationRail (dark mode) #114595

Closed sabin26 closed 1 month ago

sabin26 commented 1 year ago

Steps to Reproduce

  1. Execute flutter run on the code sample
  2. Switch to dark theme

Expected results: dark_mode_expected

Actual results: dark_mode

Code sample ```dart import 'package:flutter/material.dart'; import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorSchemeSeed: const Color(0xFFE4935D), useMaterial3: true, brightness: Brightness.light, ), darkTheme: ThemeData( colorSchemeSeed: const Color(0xFFE4935D), useMaterial3: true, brightness: Brightness.dark, ), home: const HomePage(), ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return AdaptiveScaffold( appBar: AppBar( elevation: 4, title: const Text('Demo App'), ), useDrawer: false, destinations: const [ NavigationDestination( icon: Icon(Icons.home), label: 'Home', ), NavigationDestination( icon: Icon(Icons.add_box), label: 'Counter', ), ], body: (final _) { return const SizedBox.shrink(); }, onSelectedIndexChange: (final index) {}, ); } } ```

The issue is from standardNavigationRail function in adaptive_scaffold.dart where default values for backgroundcolor, selectedIconTheme, unselectedIconTheme, selectedLabelTextStyle are provided. When removed, it works as expected.

static Builder standardNavigationRail({
    required List<NavigationRailDestination> destinations,
    double width = 72,
    int selectedIndex = 0,
    bool extended = false,
    Color backgroundColor = Colors.transparent,
    EdgeInsetsGeometry padding = const EdgeInsets.all(8.0),
    Widget? leading,
    Widget? trailing,
    Function(int)? onDestinationSelected,
    IconThemeData selectedIconTheme = const IconThemeData(color: Colors.black),
    IconThemeData unselectedIconTheme =
        const IconThemeData(color: Colors.black),
    TextStyle selectedLabelTextStyle = const TextStyle(color: Colors.black),
    NavigationRailLabelType labelType = NavigationRailLabelType.none,
  }) {
    if (extended && width == 72) {
      width = 192;
    }
    return Builder(builder: (BuildContext context) {
      return Padding(
        padding: padding,
        child: SizedBox(
          width: width,
          height: MediaQuery.of(context).size.height,
          child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return SingleChildScrollView(
                  child: ConstrainedBox(
                constraints: BoxConstraints(minHeight: constraints.maxHeight),
                child: IntrinsicHeight(
                  child: NavigationRail(
                    labelType: labelType,
                    leading: leading,
                    trailing: trailing,
                    onDestinationSelected: onDestinationSelected,
                    backgroundColor: backgroundColor, // remove this or make this parameter nullable
                    extended: extended,
                    selectedIndex: selectedIndex,
                    selectedIconTheme: selectedIconTheme, // remove this or make this parameter nullable
                    unselectedIconTheme: unselectedIconTheme, // remove this or make this parameter nullable
                    selectedLabelTextStyle: selectedLabelTextStyle, // remove this or make this parameter nullable
                    destinations: destinations,
                  ),
                ),
              ));
            },
          ),
        ),
      );
    });
exaby73 commented 1 year ago

Triage report

I can reproduce this issue with the code sample provided above on Master (3.5.0-12.0.pre.94).

Code Sample (Same as OP) ```dart import 'package:flutter/material.dart'; import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorSchemeSeed: const Color(0xFFE4935D), useMaterial3: true, brightness: Brightness.light, ), darkTheme: ThemeData( colorSchemeSeed: const Color(0xFFE4935D), useMaterial3: true, brightness: Brightness.dark, ), home: const HomePage(), ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return AdaptiveScaffold( appBar: AppBar( elevation: 4, title: const Text('Demo App'), ), useDrawer: false, destinations: const [ NavigationDestination( icon: Icon(Icons.home), label: 'Home', ), NavigationDestination( icon: Icon(Icons.add_box), label: 'Counter', ), ], body: (final _) { return const SizedBox.shrink(); }, onSelectedIndexChange: (final index) {}, ); } } ```
FelixZY commented 1 year ago

Some more screenshots. The AdaptiveScaffold seems visually broken at this time and is currently unusable for me.

Screenshots
FelixZY commented 1 year ago
  • Bottom navigation bar is completely off-m3 spec

Looks like this is caused by standardBottomNavigationBar using BottomNavigationBar instead of NavigationBar (see also https://api.flutter.dev/flutter/material/NavigationBar-class.html)

FelixZY commented 1 year ago
  • Long-press ripple reaches square bounds - I would expect rounded corners

I believe I expected large screens to use a NavigationDrawer rather than an expanded NavigationRail. Based on current documentation, an expanded NavigationRail is expected behavior, however.

lewinpauli commented 1 year ago

Thank you @sabin26 ! I just changed backgroundColor, selectedIconTheme, unselectedIconTheme, selectedLabelTextStyle to required and removed the default value. ("required" is probably not the best way to go in the long term but it works for now)

For backgroundColor I still set a default value to make it transparent and not popping up when changing the theme.

Here my adaptive_scaffold.dart file and navigation_rail.dart file to save someone some time:

adaptive_scaffold.dart ``` // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'adaptive_layout.dart'; import 'breakpoints.dart'; import 'slot_layout.dart'; /// Gutter value between different parts of the body slot depending on /// material 3 design spec. const double kMaterialGutterValue = 8; /// Margin value of the compact breakpoint layout according to the material /// design 3 spec. const double kMaterialCompactMinMargin = 8; /// Margin value of the medium breakpoint layout according to the material /// design 3 spec. const double kMaterialMediumMinMargin = 12; //// Margin value of the expanded breakpoint layout according to the material /// design 3 spec. const double kMaterialExpandedMinMargin = 32; /// Implements the basic visual layout structure for /// [Material Design 3](https://m3.material.io/foundations/adaptive-design/overview) /// that adapts to a variety of screens. /// /// !["Example of a display made with AdaptiveScaffold"](../../example/demo_files/adaptiveScaffold.gif) /// /// [AdaptiveScaffold] provides a preset of layout, including positions and /// animations, by handling macro changes in navigational elements and bodies /// based on the current features of the screen, namely screen width and platform. /// For example, the navigational elements would be a [BottomNavigationBar] on a /// small mobile device or a [Drawer] on a small desktop device and a /// [NavigationRail] on larger devices. When the app's size changes, for example /// because its window is resized, the corresponding layout transition is animated. /// The layout and navigation changes are dictated by "breakpoints" which can be /// customized or overridden. /// /// Also provides a variety of helper methods for navigational elements, /// animations, and more. /// /// [AdaptiveScaffold] is based on [AdaptiveLayout] but is easier to use at the /// cost of being less customizable. Apps that would like more refined layout /// and/or animation should use [AdaptiveLayout]. /// /// ```dart /// AdaptiveScaffold( /// destinations: const [ /// NavigationDestination(icon: Icon(Icons.inbox), label: 'Inbox'), /// NavigationDestination(icon: Icon(Icons.article), label: 'Articles'), /// NavigationDestination(icon: Icon(Icons.chat), label: 'Chat'), /// NavigationDestination(icon: Icon(Icons.video_call), label: 'Video'), /// ], /// smallBody: (_) => ListView.builder( /// itemCount: children.length, /// itemBuilder: (_, idx) => children[idx] /// ), /// body: (_) => GridView.count(crossAxisCount: 2, children: children), /// ), /// ``` /// /// See also: /// /// * [AdaptiveLayout], which is what this widget is built upon internally and /// acts as a more customizable alternative. /// * [SlotLayout], which handles switching and animations between elements /// based on [Breakpoint]s. /// * [SlotLayout.from], which holds information regarding Widgets and the /// desired way to animate between switches. Often used within [SlotLayout]. /// * [Design Doc](https://flutter.dev/go/adaptive-layout-foldables). /// * [Material Design 3 Specifications] (https://m3.material.io/foundations/adaptive-design/overview). class AdaptiveScaffold extends StatefulWidget { /// Returns a const [AdaptiveScaffold] by passing information down to an /// [AdaptiveLayout]. const AdaptiveScaffold({ super.key, required this.destinations, required this.backgroundColor, required this.selectedLabelTextStyle, required this.selectedIconTheme, required this.unselectedIconTheme, this.selectedIndex = 0, this.leadingUnextendedNavRail, this.leadingExtendedNavRail, this.trailingNavRail, this.smallBody, this.body, this.largeBody, this.smallSecondaryBody, this.secondaryBody, this.largeSecondaryBody, this.bodyRatio, this.smallBreakpoint = Breakpoints.small, this.mediumBreakpoint = Breakpoints.medium, this.largeBreakpoint = Breakpoints.large, this.drawerBreakpoint = Breakpoints.smallDesktop, this.internalAnimations = true, this.bodyOrientation = Axis.horizontal, this.onSelectedIndexChange, this.useDrawer = true, this.appBar, this.navigationRailWidth = 72, this.extendedNavigationRailWidth = 192, }); final Color backgroundColor; final TextStyle selectedLabelTextStyle; final IconThemeData selectedIconTheme; final IconThemeData unselectedIconTheme; /// The destinations to be used in navigation items. These are converted to /// [NavigationRailDestination]s and [BottomNavigationBarItem]s and inserted /// into the appropriate places. If passing destinations, you must also pass a /// selected index to be used by the [NavigationRail]. final List destinations; /// The index to be used by the [NavigationRail]. final int? selectedIndex; /// Option to display a leading widget at the top of the navigation rail /// at the middle breakpoint. final Widget? leadingUnextendedNavRail; /// Option to display a leading widget at the top of the navigation rail /// at the largest breakpoint. final Widget? leadingExtendedNavRail; /// Option to display a trailing widget below the destinations of the /// navigation rail at the largest breakpoint. final Widget? trailingNavRail; /// Widget to be displayed in the body slot at the smallest breakpoint. /// /// If nothing is entered for this property, then the default [body] is /// displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? smallBody; /// Widget to be displayed in the body slot at the middle breakpoint. /// /// The default displayed body. final WidgetBuilder? body; /// Widget to be displayed in the body slot at the largest breakpoint. /// /// If nothing is entered for this property, then the default [body] is /// displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? largeBody; /// Widget to be displayed in the secondaryBody slot at the smallest /// breakpoint. /// /// If nothing is entered for this property, then the default [secondaryBody] /// is displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? smallSecondaryBody; /// Widget to be displayed in the secondaryBody slot at the middle breakpoint. /// /// The default displayed secondaryBody. final WidgetBuilder? secondaryBody; /// Widget to be displayed in the secondaryBody slot at the largest /// breakpoint. /// /// If nothing is entered for this property, then the default [secondaryBody] /// is displayed in the slot. If null is entered for this slot, the slot stays /// empty. final WidgetBuilder? largeSecondaryBody; /// Defines the fractional ratio of body to the secondaryBody. /// /// For example 0.3 would mean body takes up 30% of the available space and /// secondaryBody takes up the rest. /// /// If this value is null, the ratio is defined so that the split axis is in /// the center of the screen. final double? bodyRatio; /// The breakpoint defined for the small size, associated with mobile-like /// features. /// /// Defaults to [Breakpoints.small]. final Breakpoint smallBreakpoint; /// The breakpoint defined for the medium size, associated with tablet-like /// features. /// /// Defaults to [Breakpoints.mediumBreakpoint]. final Breakpoint mediumBreakpoint; /// The breakpoint defined for the large size, associated with desktop-like /// features. /// /// Defaults to [Breakpoints.largeBreakpoint]. final Breakpoint largeBreakpoint; /// Whether or not the developer wants the smooth entering slide transition on /// secondaryBody. /// /// Defaults to true. final bool internalAnimations; /// The orientation of the body and secondaryBody. Either horizontal (side by /// side) or vertical (top to bottom). /// /// Defaults to Axis.horizontal. final Axis bodyOrientation; /// Whether to use a [Drawer] over a [BottomNavigationBar] when not on mobile /// and Breakpoint is small. /// /// Defaults to true. final bool useDrawer; /// Option to override the drawerBreakpoint for the usage of [Drawer] over the /// usual [BottomNavigationBar]. /// /// Defaults to [Breakpoints.smallDesktop]. final Breakpoint drawerBreakpoint; /// Option to override the default [AppBar] when using drawer in desktop /// small. final PreferredSizeWidget? appBar; /// Callback function for when the index of a [NavigationRail] changes. final Function(int)? onSelectedIndexChange; /// The width used for the internal [NavigationRail] at the medium [Breakpoint]. final double navigationRailWidth; /// The width used for the internal extended [NavigationRail] at the large /// [Breakpoint]. final double extendedNavigationRailWidth; /// Callback function for when the index of a [NavigationRail] changes. static WidgetBuilder emptyBuilder = (_) => const SizedBox(); /// Public helper method to be used for creating a [NavigationRailDestination] from /// a [NavigationDestination]. static NavigationRailDestination toRailDestination( NavigationDestination destination) { return NavigationRailDestination( label: Text(destination.label), icon: destination.icon, ); } /// Creates a Material 3 Design Spec abiding [NavigationRail] from a /// list of [NavigationDestination]s. /// /// Takes in a [selectedIndex] property for the current selected item in /// the [NavigationRail] and [extended] for whether the [NavigationRail] /// is extended or not. static Builder standardNavigationRail({ required List destinations, double width = 72, int? selectedIndex, bool extended = false, Color backgroundColor = Colors.transparent, EdgeInsetsGeometry padding = const EdgeInsets.all(8.0), Widget? leading, Widget? trailing, Function(int)? onDestinationSelected, required IconThemeData selectedIconTheme, required IconThemeData unselectedIconTheme, required TextStyle selectedLabelTextStyle, NavigationRailLabelType labelType = NavigationRailLabelType.none, }) { if (extended && width == 72) { width = 192; } return Builder(builder: (BuildContext context) { return Padding( padding: padding, child: SizedBox( width: width, height: MediaQuery.of(context).size.height, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints(minHeight: constraints.maxHeight), child: IntrinsicHeight( child: NavigationRail( labelType: labelType, leading: leading, trailing: trailing, onDestinationSelected: onDestinationSelected, backgroundColor: backgroundColor, extended: extended, selectedIndex: selectedIndex, selectedIconTheme: selectedIconTheme, unselectedIconTheme: unselectedIconTheme, selectedLabelTextStyle: selectedLabelTextStyle, destinations: destinations, ), ), )); }, ), ), ); }); } /// Public helper method to be used for creating a [BottomNavigationBar] from /// a list of [NavigationDestination]s. static Builder standardBottomNavigationBar({ required List destinations, int? currentIndex, double iconSize = 24, ValueChanged? onDestinationSelected, }) { currentIndex ??= 0; return Builder( builder: (_) { return BottomNavigationBar( currentIndex: currentIndex ?? 0, iconSize: iconSize, items: destinations .map((NavigationDestination e) => _toBottomNavItem(e)) .toList(), onTap: onDestinationSelected, ); }, ); } /// Public helper method to be used for creating a staggered grid following m3 /// specs from a list of [Widget]s static Builder toMaterialGrid({ List thisWidgets = const [], List breakpoints = const [ Breakpoints.small, Breakpoints.medium, Breakpoints.large, ], double margin = 8, int itemColumns = 1, required BuildContext context, }) { return Builder(builder: (BuildContext context) { Breakpoint? currentBreakpoint; for (final Breakpoint breakpoint in breakpoints) { if (breakpoint.isActive(context)) { currentBreakpoint = breakpoint; } } double? thisMargin = margin; if (currentBreakpoint == Breakpoints.small) { if (thisMargin < kMaterialCompactMinMargin) { thisMargin = kMaterialCompactMinMargin; } } else if (currentBreakpoint == Breakpoints.medium) { if (thisMargin < kMaterialMediumMinMargin) { thisMargin = kMaterialMediumMinMargin; } } else if (currentBreakpoint == Breakpoints.large) { if (thisMargin < kMaterialExpandedMinMargin) { thisMargin = kMaterialExpandedMinMargin; } } return CustomScrollView( primary: false, controller: ScrollController(), shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), slivers: [ SliverToBoxAdapter( child: Padding( padding: EdgeInsets.all(thisMargin), child: _BrickLayout( columns: itemColumns, columnSpacing: kMaterialGutterValue, itemPadding: const EdgeInsets.only(bottom: kMaterialGutterValue), children: thisWidgets, ), ), ), ], ); }); } /// Animation from bottom offscreen up onto the screen. static AnimatedWidget bottomToTop(Widget child, Animation animation) { return SlideTransition( position: Tween( begin: const Offset(0, 1), end: Offset.zero, ).animate(animation), child: child, ); } /// Animation from on the screen down off the screen. static AnimatedWidget topToBottom(Widget child, Animation animation) { return SlideTransition( position: Tween( begin: Offset.zero, end: const Offset(0, 1), ).animate(animation), child: child, ); } /// Animation from left off the screen into the screen. static AnimatedWidget leftOutIn(Widget child, Animation animation) { return SlideTransition( position: Tween( begin: const Offset(-1, 0), end: Offset.zero, ).animate(animation), child: child, ); } /// Animation from on screen to left off screen. static AnimatedWidget leftInOut(Widget child, Animation animation) { return SlideTransition( position: Tween( begin: Offset.zero, end: const Offset(-1, 0), ).animate(animation), child: child, ); } /// Animation from right off screen to on screen. static AnimatedWidget rightOutIn(Widget child, Animation animation) { return SlideTransition( position: Tween( begin: const Offset(1, 0), end: Offset.zero, ).animate(animation), child: child, ); } /// Fade in animation. static Widget fadeIn(Widget child, Animation animation) { return FadeTransition( opacity: CurvedAnimation(parent: animation, curve: Curves.easeInCubic), child: child, ); } /// Fade out animation. static Widget fadeOut(Widget child, Animation animation) { return FadeTransition( opacity: CurvedAnimation( parent: ReverseAnimation(animation), curve: Curves.easeInCubic, ), child: child, ); } /// Keep widget on screen while it is leaving static Widget stayOnScreen(Widget child, Animation animation) { return FadeTransition( opacity: Tween(begin: 1.0, end: 1.0).animate(animation), child: child, ); } @override State createState() => _AdaptiveScaffoldState(); } class _AdaptiveScaffoldState extends State { @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Scaffold( appBar: widget.drawerBreakpoint.isActive(context) && widget.useDrawer ? widget.appBar ?? AppBar() : null, drawer: widget.drawerBreakpoint.isActive(context) && widget.useDrawer ? Drawer( child: NavigationRail( selectedLabelTextStyle: widget.selectedLabelTextStyle, selectedIconTheme: widget.selectedIconTheme, unselectedIconTheme: widget.unselectedIconTheme, backgroundColor: widget.backgroundColor, extended: true, leading: widget.leadingExtendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((_) => AdaptiveScaffold.toRailDestination(_)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, ), ) : null, body: AdaptiveLayout( bodyOrientation: widget.bodyOrientation, bodyRatio: widget.bodyRatio, internalAnimations: widget.internalAnimations, primaryNavigation: SlotLayout( config: { widget.mediumBreakpoint: SlotLayout.from( key: const Key('primaryNavigation'), builder: (_) => AdaptiveScaffold.standardNavigationRail( backgroundColor: widget.backgroundColor, unselectedIconTheme: widget.unselectedIconTheme, selectedIconTheme: widget.selectedIconTheme, selectedLabelTextStyle: widget.selectedLabelTextStyle, width: widget.navigationRailWidth, leading: widget.leadingUnextendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((_) => AdaptiveScaffold.toRailDestination(_)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, ), ), widget.largeBreakpoint: SlotLayout.from( key: const Key('primaryNavigation1'), builder: (_) => AdaptiveScaffold.standardNavigationRail( backgroundColor: widget.backgroundColor, unselectedIconTheme: widget.unselectedIconTheme, selectedIconTheme: widget.selectedIconTheme, selectedLabelTextStyle: widget.selectedLabelTextStyle, width: widget.extendedNavigationRailWidth, extended: true, leading: widget.leadingExtendedNavRail, trailing: widget.trailingNavRail, selectedIndex: widget.selectedIndex, destinations: widget.destinations .map((_) => AdaptiveScaffold.toRailDestination(_)) .toList(), onDestinationSelected: widget.onSelectedIndexChange, ), ), }, ), bottomNavigation: !widget.drawerBreakpoint.isActive(context) || !widget.useDrawer ? SlotLayout( config: { widget.smallBreakpoint: SlotLayout.from( key: const Key('bottomNavigation'), builder: (_) => AdaptiveScaffold.standardBottomNavigationBar( currentIndex: widget.selectedIndex, destinations: widget.destinations, onDestinationSelected: widget.onSelectedIndexChange, ), ), }, ) : null, body: SlotLayout( config: { Breakpoints.standard: SlotLayout.from( key: const Key('body'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.body, ), if (widget.smallBody != null) widget.smallBreakpoint: (widget.smallBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('smallBody'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.smallBody, ) : null, if (widget.body != null) widget.mediumBreakpoint: (widget.body != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('body'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.body, ) : null, if (widget.largeBody != null) widget.largeBreakpoint: (widget.largeBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('largeBody'), inAnimation: AdaptiveScaffold.fadeIn, outAnimation: AdaptiveScaffold.fadeOut, builder: widget.largeBody, ) : null, }, ), secondaryBody: SlotLayout( config: { Breakpoints.standard: SlotLayout.from( key: const Key('sBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.secondaryBody, ), if (widget.smallSecondaryBody != null) widget.smallBreakpoint: (widget.smallSecondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('smallSBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.smallSecondaryBody, ) : null, if (widget.secondaryBody != null) widget.mediumBreakpoint: (widget.secondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('sBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.secondaryBody, ) : null, if (widget.largeSecondaryBody != null) widget.largeBreakpoint: (widget.largeSecondaryBody != AdaptiveScaffold.emptyBuilder) ? SlotLayout.from( key: const Key('largeSBody'), outAnimation: AdaptiveScaffold.stayOnScreen, builder: widget.largeSecondaryBody, ) : null, }, ), ), ), ); } } BottomNavigationBarItem _toBottomNavItem(NavigationDestination destination) { return BottomNavigationBarItem( label: destination.label, icon: destination.icon, ); } class _BrickLayout extends StatelessWidget { const _BrickLayout({ this.columns = 1, this.itemPadding = EdgeInsets.zero, this.columnSpacing = 0, required this.children, }); final int columns; final double columnSpacing; final EdgeInsetsGeometry itemPadding; final List children; @override Widget build(BuildContext context) { int i = -1; return Column( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: CustomMultiChildLayout( delegate: _BrickLayoutDelegate( columns: columns, columnSpacing: columnSpacing, itemPadding: itemPadding, ), children: children .map( (Widget child) => LayoutId(id: i += 1, child: child), ) .toList(), ), ), ], ); } } class _BrickLayoutDelegate extends MultiChildLayoutDelegate { _BrickLayoutDelegate({ this.columns = 1, this.columnSpacing = 0, this.itemPadding = EdgeInsets.zero, }); final int columns; final EdgeInsetsGeometry itemPadding; final double columnSpacing; @override void performLayout(Size size) { final BoxConstraints looseConstraints = BoxConstraints.loose(size); final BoxConstraints fullWidthConstraints = looseConstraints.tighten(width: size.width); final List childSizes = []; int childCount = 0; // Count how many children we have. for (; hasChild(childCount); childCount += 1) {} final BoxConstraints itemConstraints = BoxConstraints( maxWidth: fullWidthConstraints.maxWidth / columns - columnSpacing / 2 - itemPadding.horizontal, ); for (int i = 0; i < childCount; i += 1) { childSizes.add(layoutChild(i, itemConstraints)); } int columnIndex = 0; int childId = 0; final double totalColumnSpacing = columnSpacing * (columns - 1); final double columnWidth = (size.width - totalColumnSpacing) / columns; final double topPadding = itemPadding.resolve(TextDirection.ltr).top; final List columnUsage = List.generate(columns, (int index) => topPadding); for (final Size childSize in childSizes) { positionChild( childId, Offset( columnSpacing * columnIndex + columnWidth * columnIndex + (columnWidth - childSize.width) / 2, columnUsage[columnIndex], ), ); columnUsage[columnIndex] += childSize.height + itemPadding.vertical; columnIndex = (columnIndex + 1) % columns; childId += 1; } } @override bool shouldRelayout(_BrickLayoutDelegate oldDelegate) { return itemPadding != oldDelegate.itemPadding || columnSpacing != oldDelegate.columnSpacing; } } ```
navigation_rail.dart ``` // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_localizations.dart'; import 'navigation_bar.dart'; import 'navigation_rail_theme.dart'; import 'text_theme.dart'; import 'theme.dart'; const double _kCircularIndicatorDiameter = 56; const double _kIndicatorHeight = 32; /// A Material Design widget that is meant to be displayed at the left or right of an /// app to navigate between a small number of views, typically between three and /// five. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=y9xchtVTtqQ} /// /// The navigation rail is meant for layouts with wide viewports, such as a /// desktop web or tablet landscape layout. For smaller layouts, like mobile /// portrait, a [BottomNavigationBar] should be used instead. /// /// A navigation rail is usually used as the first or last element of a [Row] /// which defines the app's [Scaffold] body. /// /// The appearance of all of the [NavigationRail]s within an app can be /// specified with [NavigationRailTheme]. The default values for null theme /// properties are based on the [Theme]'s [ThemeData.textTheme], /// [ThemeData.iconTheme], and [ThemeData.colorScheme]. /// /// Adaptive layouts can build different instances of the [Scaffold] in order to /// have a navigation rail for more horizontal layouts and a bottom navigation /// bar for more vertical layouts. See /// [the adaptive_scaffold.dart sample](https://github.com/flutter/samples/blob/master/experimental/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart) /// for an example. /// /// {@tool dartpad} /// This example shows a [NavigationRail] used within a Scaffold with 3 /// [NavigationRailDestination]s. The main content is separated by a divider /// (although elevation on the navigation rail can be used instead). The /// `_selectedIndex` is updated by the `onDestinationSelected` callback. /// /// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This sample shows the creation of [NavigationRail] widget used within a Scaffold with 3 /// [NavigationRailDestination]s, as described in: https://m3.material.io/components/navigation-rail/overview /// /// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.1.dart ** /// {@end-tool} /// /// See also: /// /// * [Scaffold], which can display the navigation rail within a [Row] of the /// [Scaffold.body] slot. /// * [NavigationRailDestination], which is used as a model to create tappable /// destinations in the navigation rail. /// * [BottomNavigationBar], which is a similar navigation widget that's laid /// out horizontally. /// * /// * class NavigationRail extends StatefulWidget { /// Creates a Material Design navigation rail. /// /// The value of [destinations] must be a list of two or more /// [NavigationRailDestination] values. /// /// If [elevation] is specified, it must be non-negative. /// /// If [minWidth] is specified, it must be non-negative, and if /// [minExtendedWidth] is specified, it must be non-negative and greater than /// [minWidth]. /// /// The argument [extended] must not be null. [extended] can only be set to /// true when the [labelType] is null or [NavigationRailLabelType.none]. /// /// If [backgroundColor], [elevation], [groupAlignment], [labelType], /// [unselectedLabelTextStyle], [selectedLabelTextStyle], /// [unselectedIconTheme], or [selectedIconTheme] are null, then their /// [NavigationRailThemeData] values will be used. If the corresponding /// [NavigationRailThemeData] property is null, then the navigation rail /// defaults are used. See the individual properties for more information. /// /// Typically used within a [Row] that defines the [Scaffold.body] property. NavigationRail({ super.key, this.backgroundColor, this.extended = false, this.leading, this.trailing, required this.destinations, required this.selectedIndex, this.onDestinationSelected, this.elevation, this.groupAlignment, this.labelType, this.unselectedLabelTextStyle, required this.selectedLabelTextStyle, required this.unselectedIconTheme, required this.selectedIconTheme, this.minWidth, this.minExtendedWidth, this.useIndicator, this.indicatorColor, }) : assert(destinations != null && destinations.length >= 2), assert(selectedIndex == null || (0 <= selectedIndex && selectedIndex < destinations.length)), assert(elevation == null || elevation > 0), assert(minWidth == null || minWidth > 0), assert(minExtendedWidth == null || minExtendedWidth > 0), assert((minWidth == null || minExtendedWidth == null) || minExtendedWidth >= minWidth), assert(extended != null), assert(!extended || (labelType == null || labelType == NavigationRailLabelType.none)); /// Sets the color of the Container that holds all of the [NavigationRail]'s /// contents. /// /// The default value is [NavigationRailThemeData.backgroundColor]. If /// [NavigationRailThemeData.backgroundColor] is null, then the default value /// is based on [ColorScheme.surface] of [ThemeData.colorScheme]. final Color? backgroundColor; /// Defines the appearance of the button items that are arrayed within the /// navigation rail. /// /// The value must be a list of two or more [NavigationRailDestination] /// values. final List destinations; /// The rail's elevation or z-coordinate. /// /// If [Directionality] is [intl.TextDirection.LTR], the inner side is the /// right side, and if [Directionality] is [intl.TextDirection.RTL], it is /// the left side. /// /// The default value is 0. final double? elevation; /// Indicates that the [NavigationRail] should be in the extended state. /// /// The extended state has a wider rail container, and the labels are /// positioned next to the icons. [minExtendedWidth] can be used to set the /// minimum width of the rail when it is in this state. /// /// The rail will implicitly animate between the extended and normal state. /// /// If the rail is going to be in the extended state, then the [labelType] /// must be set to [NavigationRailLabelType.none]. /// /// The default value is false. final bool extended; /// The vertical alignment for the group of [destinations] within the rail. /// /// The [NavigationRailDestination]s are grouped together with the [trailing] /// widget, between the [leading] widget and the bottom of the rail. /// /// The value must be between -1.0 and 1.0. /// /// If [groupAlignment] is -1.0, then the items are aligned to the top. If /// [groupAlignment] is 0.0, then the items are aligned to the center. If /// [groupAlignment] is 1.0, then the items are aligned to the bottom. /// /// The default is -1.0. /// /// See also: /// * [Alignment.y] /// final double? groupAlignment; /// Overrides the default value of [NavigationRail]'s selection indicator color, /// when [useIndicator] is true. final Color? indicatorColor; /// Defines the layout and behavior of the labels for the default, unextended /// [NavigationRail]. /// /// When a navigation rail is [extended], the labels are always shown. /// /// The default value is [NavigationRailThemeData.labelType]. If /// [NavigationRailThemeData.labelType] is null, then the default value is /// [NavigationRailLabelType.none]. /// /// See also: /// /// * [NavigationRailLabelType] for information on the meaning of different /// types. final NavigationRailLabelType? labelType; /// The leading widget in the rail that is placed above the destinations. /// /// It is placed at the top of the rail, above the [destinations]. Its /// location is not affected by [groupAlignment]. /// /// This is commonly a [FloatingActionButton], but may also be a non-button, /// such as a logo. /// /// The default value is null. final Widget? leading; /// The final width when the animation is complete for setting [extended] to /// true. /// /// This is only used when [extended] is set to true. /// /// The default value is 256. final double? minExtendedWidth; /// The smallest possible width for the rail regardless of the destination's /// icon or label size. /// /// The default is 72. /// /// This value also defines the min width and min height of the destinations. /// /// To make a compact rail, set this to 56 and use /// [NavigationRailLabelType.none]. final double? minWidth; /// Called when one of the [destinations] is selected. /// /// The stateful widget that creates the navigation rail needs to keep /// track of the index of the selected [NavigationRailDestination] and call /// `setState` to rebuild the navigation rail with the new [selectedIndex]. final ValueChanged? onDestinationSelected; /// The visual properties of the icon in the selected destination. /// /// When a [NavigationRailDestination] is not selected, /// [unselectedIconTheme] will be used. /// /// The default value is the [Theme]'s [ThemeData.iconTheme] with a color /// of the [Theme]'s [ColorScheme.primary]. Properties from this icon theme, /// or [NavigationRailThemeData.selectedIconTheme] if this is null, are /// merged into the defaults. final IconThemeData? selectedIconTheme; /// The index into [destinations] for the current selected /// [NavigationRailDestination] or null if no destination is selected. final int? selectedIndex; /// The [TextStyle] of a destination's label when it is selected. /// /// When a [NavigationRailDestination] is not selected, /// [unselectedLabelTextStyle] will be used. /// /// The default value is based on the [TextTheme.bodyLarge] of /// [ThemeData.textTheme]. The default color is based on the [Theme]'s /// [ColorScheme.primary]. /// /// Properties from this text style, /// or [NavigationRailThemeData.selectedLabelTextStyle] if this is null, are /// merged into the defaults. final TextStyle? selectedLabelTextStyle; /// The trailing widget in the rail that is placed below the destinations. /// /// The trailing widget is placed below the last [NavigationRailDestination]. /// It's location is affected by [groupAlignment]. /// /// This is commonly a list of additional options or destinations that is /// usually only rendered when [extended] is true. /// /// The default value is null. final Widget? trailing; /// The visual properties of the icon in the unselected destination. /// /// If this field is not provided, or provided with any null properties, then /// a copy of the [IconThemeData.fallback] with a custom [NavigationRail] /// specific color will be used. /// /// The default value is the [Theme]'s [ThemeData.iconTheme] with a color /// of the [Theme]'s [ColorScheme.onSurface] with an opacity of 0.64. /// Properties from this icon theme, or /// [NavigationRailThemeData.unselectedIconTheme] if this is null, are /// merged into the defaults. final IconThemeData? unselectedIconTheme; /// The [TextStyle] of a destination's label when it is unselected. /// /// When one of the [destinations] is selected the [selectedLabelTextStyle] /// will be used instead. /// /// The default value is based on the [Theme]'s [TextTheme.bodyLarge]. The /// default color is based on the [Theme]'s [ColorScheme.onSurface]. /// /// Properties from this text style, or /// [NavigationRailThemeData.unselectedLabelTextStyle] if this is null, are /// merged into the defaults. final TextStyle? unselectedLabelTextStyle; /// If `true`, adds a rounded [NavigationIndicator] behind the selected /// destination's icon. /// /// The indicator's shape will be circular if [labelType] is /// [NavigationRailLabelType.none], or a [StadiumBorder] if [labelType] is /// [NavigationRailLabelType.all] or [NavigationRailLabelType.selected]. /// /// If `null`, defaults to [NavigationRailThemeData.useIndicator]. If that is /// `null`, defaults to [ThemeData.useMaterial3]. final bool? useIndicator; @override State createState() => _NavigationRailState(); /// Returns the animation that controls the [NavigationRail.extended] state. /// /// This can be used to synchronize animations in the [leading] or [trailing] /// widget, such as an animated menu or a [FloatingActionButton] animation. /// /// {@tool dartpad} /// This example shows how to use this animation to create a [FloatingActionButton] /// that animates itself between the normal and extended states of the /// [NavigationRail]. /// /// An instance of `MyNavigationRailFab` is created for [NavigationRail.leading]. /// Pressing the FAB button toggles the "extended" state of the [NavigationRail]. /// /// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.extended_animation.0.dart ** /// {@end-tool} static Animation extendedAnimation(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<_ExtendedNavigationRailAnimation>()!.animation; } } class _NavigationRailState extends State with TickerProviderStateMixin { late List> _destinationAnimations; late List _destinationControllers; late Animation _extendedAnimation; late AnimationController _extendedController; @override void didUpdateWidget(NavigationRail oldWidget) { super.didUpdateWidget(oldWidget); if (widget.extended != oldWidget.extended) { if (widget.extended) { _extendedController.forward(); } else { _extendedController.reverse(); } } // No animated segue if the length of the items list changes. if (widget.destinations.length != oldWidget.destinations.length) { _resetState(); return; } if (widget.selectedIndex != oldWidget.selectedIndex) { if (oldWidget.selectedIndex != null) { _destinationControllers[oldWidget.selectedIndex!].reverse(); } if (widget.selectedIndex != null) { _destinationControllers[widget.selectedIndex!].forward(); } return; } } @override void dispose() { _disposeControllers(); super.dispose(); } @override void initState() { super.initState(); _initControllers(); } void _disposeControllers() { for (final AnimationController controller in _destinationControllers) { controller.dispose(); } _extendedController.dispose(); } void _initControllers() { _destinationControllers = List.generate(widget.destinations.length, (int index) { return AnimationController( duration: kThemeAnimationDuration, vsync: this, )..addListener(_rebuild); }); _destinationAnimations = _destinationControllers.map((AnimationController controller) => controller.view).toList(); if (widget.selectedIndex != null) { _destinationControllers[widget.selectedIndex!].value = 1.0; } _extendedController = AnimationController( duration: kThemeAnimationDuration, vsync: this, value: widget.extended ? 1.0 : 0.0, ); _extendedAnimation = CurvedAnimation( parent: _extendedController, curve: Curves.easeInOut, ); _extendedController.addListener(() { _rebuild(); }); } void _resetState() { _disposeControllers(); _initControllers(); } void _rebuild() { setState(() { // Rebuilding when any of the controllers tick, i.e. when the items are // animating. }); } @override Widget build(BuildContext context) { final NavigationRailThemeData navigationRailTheme = NavigationRailTheme.of(context); final NavigationRailThemeData defaults = Theme.of(context).useMaterial3 ? _NavigationRailDefaultsM3(context) : _NavigationRailDefaultsM2(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Color backgroundColor = widget.backgroundColor ?? navigationRailTheme.backgroundColor ?? defaults.backgroundColor!; final double elevation = widget.elevation ?? navigationRailTheme.elevation ?? defaults.elevation!; final double minWidth = widget.minWidth ?? navigationRailTheme.minWidth ?? defaults.minWidth!; final double minExtendedWidth = widget.minExtendedWidth ?? navigationRailTheme.minExtendedWidth ?? defaults.minExtendedWidth!; final TextStyle unselectedLabelTextStyle = widget.unselectedLabelTextStyle ?? navigationRailTheme.unselectedLabelTextStyle ?? defaults.unselectedLabelTextStyle!; final TextStyle selectedLabelTextStyle = widget.selectedLabelTextStyle ?? navigationRailTheme.selectedLabelTextStyle ?? defaults.selectedLabelTextStyle!; final IconThemeData unselectedIconTheme = widget.unselectedIconTheme ?? navigationRailTheme.unselectedIconTheme ?? defaults.unselectedIconTheme!; final IconThemeData selectedIconTheme = widget.selectedIconTheme ?? navigationRailTheme.selectedIconTheme ?? defaults.selectedIconTheme!; final double groupAlignment = widget.groupAlignment ?? navigationRailTheme.groupAlignment ?? defaults.groupAlignment!; final NavigationRailLabelType labelType = widget.labelType ?? navigationRailTheme.labelType ?? defaults.labelType!; final bool useIndicator = widget.useIndicator ?? navigationRailTheme.useIndicator ?? defaults.useIndicator!; final Color? indicatorColor = widget.indicatorColor ?? navigationRailTheme.indicatorColor ?? defaults.indicatorColor; final ShapeBorder? indicatorShape = navigationRailTheme.indicatorShape ?? defaults.indicatorShape; // For backwards compatibility, in M2 the opacity of the unselected icons needs // to be set to the default if it isn't in the given theme. This can be removed // when Material 3 is the default. final IconThemeData effectiveUnselectedIconTheme = Theme.of(context).useMaterial3 ? unselectedIconTheme : unselectedIconTheme.copyWith(opacity: unselectedIconTheme.opacity ?? defaults.unselectedIconTheme!.opacity); final bool isRTLDirection = Directionality.of(context) == TextDirection.rtl; return _ExtendedNavigationRailAnimation( animation: _extendedAnimation, child: Semantics( explicitChildNodes: true, child: Material( elevation: elevation, color: backgroundColor, child: SafeArea( right: isRTLDirection, left: !isRTLDirection, child: Column( children: [ _verticalSpacer, if (widget.leading != null) ...[ widget.leading!, _verticalSpacer, ], Expanded( child: Align( alignment: Alignment(0, groupAlignment), child: Column( mainAxisSize: MainAxisSize.min, children: [ for (int i = 0; i < widget.destinations.length; i += 1) _RailDestination( minWidth: minWidth, minExtendedWidth: minExtendedWidth, extendedTransitionAnimation: _extendedAnimation, selected: widget.selectedIndex == i, icon: widget.selectedIndex == i ? widget.destinations[i].selectedIcon : widget.destinations[i].icon, label: widget.destinations[i].label, destinationAnimation: _destinationAnimations[i], labelType: labelType, iconTheme: widget.selectedIndex == i ? selectedIconTheme : effectiveUnselectedIconTheme, labelTextStyle: widget.selectedIndex == i ? selectedLabelTextStyle : unselectedLabelTextStyle, padding: widget.destinations[i].padding, useIndicator: useIndicator, indicatorColor: useIndicator ? indicatorColor : null, indicatorShape: useIndicator ? indicatorShape : null, onTap: () { if (widget.onDestinationSelected != null) { widget.onDestinationSelected!(i); } }, indexLabel: localizations.tabLabel( tabIndex: i + 1, tabCount: widget.destinations.length, ), ), if (widget.trailing != null) widget.trailing!, ], ), ), ), ], ), ), ), ), ); } } class _RailDestination extends StatelessWidget { _RailDestination({ required this.minWidth, required this.minExtendedWidth, required this.icon, required this.label, required this.destinationAnimation, required this.extendedTransitionAnimation, required this.labelType, required this.selected, required this.iconTheme, required this.labelTextStyle, required this.onTap, required this.indexLabel, this.padding, required this.useIndicator, this.indicatorColor, this.indicatorShape, }) : assert(minWidth != null), assert(minExtendedWidth != null), assert(icon != null), assert(label != null), assert(destinationAnimation != null), assert(extendedTransitionAnimation != null), assert(labelType != null), assert(selected != null), assert(iconTheme != null), assert(labelTextStyle != null), assert(onTap != null), assert(indexLabel != null), _positionAnimation = CurvedAnimation( parent: ReverseAnimation(destinationAnimation), curve: Curves.easeInOut, reverseCurve: Curves.easeInOut.flipped, ); final Animation destinationAnimation; final Animation extendedTransitionAnimation; final Widget icon; final IconThemeData iconTheme; final String indexLabel; final Color? indicatorColor; final ShapeBorder? indicatorShape; final Widget label; final TextStyle labelTextStyle; final NavigationRailLabelType labelType; final double minExtendedWidth; final double minWidth; final VoidCallback onTap; final EdgeInsetsGeometry? padding; final bool selected; final bool useIndicator; final Animation _positionAnimation; @override Widget build(BuildContext context) { assert( useIndicator || indicatorColor == null, '[NavigationRail.indicatorColor] does not have an effect when [NavigationRail.useIndicator] is false', ); final bool material3 = Theme.of(context).useMaterial3; final EdgeInsets destionationPadding = (padding ?? EdgeInsets.zero).resolve(Directionality.of(context)); Offset indicatorOffset; final Widget themedIcon = IconTheme( data: iconTheme, child: icon, ); final Widget styledLabel = DefaultTextStyle( style: labelTextStyle, child: label, ); Widget content; switch (labelType) { case NavigationRailLabelType.none: // Split the destination spacing across the top and bottom to keep the icon centered. final Widget? spacing = material3 ? const SizedBox(height: _verticalDestinationSpacingM3 / 2) : null; indicatorOffset = Offset( minWidth / 2 + destionationPadding.left, _verticalDestinationSpacingM3 / 2 + destionationPadding.top, ); final Widget iconPart = Column( children: [ if (spacing != null) spacing, SizedBox( width: minWidth, height: material3 ? null : minWidth, child: Center( child: _AddIndicator( addIndicator: useIndicator, indicatorColor: indicatorColor, indicatorShape: indicatorShape, isCircular: !material3, indicatorAnimation: destinationAnimation, child: themedIcon, ), ), ), if (spacing != null) spacing, ], ); if (extendedTransitionAnimation.value == 0) { content = Padding( padding: padding ?? EdgeInsets.zero, child: Stack( children: [ iconPart, // For semantics when label is not showing, SizedBox( width: 0, height: 0, child: Visibility.maintain( visible: false, child: label, ), ), ], ), ); } else { final Animation labelFadeAnimation = extendedTransitionAnimation.drive(CurveTween(curve: const Interval(0.0, 0.25))); content = Padding( padding: padding ?? EdgeInsets.zero, child: ConstrainedBox( constraints: BoxConstraints( minWidth: lerpDouble(minWidth, minExtendedWidth, extendedTransitionAnimation.value)!, ), child: ClipRect( child: Row( children: [ iconPart, Align( heightFactor: 1.0, widthFactor: extendedTransitionAnimation.value, alignment: AlignmentDirectional.centerStart, child: FadeTransition( alwaysIncludeSemantics: true, opacity: labelFadeAnimation, child: styledLabel, ), ), SizedBox(width: _horizontalDestinationPadding * extendedTransitionAnimation.value), ], ), ), ), ); } break; case NavigationRailLabelType.selected: final double appearingAnimationValue = 1 - _positionAnimation.value; final double verticalPadding = lerpDouble(_verticalDestinationPaddingNoLabel, _verticalDestinationPaddingWithLabel, appearingAnimationValue)!; final Interval interval = selected ? const Interval(0.25, 0.75) : const Interval(0.75, 1.0); final Animation labelFadeAnimation = destinationAnimation.drive(CurveTween(curve: interval)); final double minHeight = material3 ? 0 : minWidth; final Widget topSpacing = SizedBox(height: material3 ? 0 : verticalPadding); final Widget labelSpacing = SizedBox(height: material3 ? lerpDouble(0, _verticalIconLabelSpacingM3, appearingAnimationValue)! : 0); final Widget bottomSpacing = SizedBox(height: material3 ? _verticalDestinationSpacingM3 : verticalPadding); final double indicatorHorizontalPadding = (destionationPadding.left / 2) - (destionationPadding.right / 2); final double indicatorVerticalPadding = destionationPadding.top; indicatorOffset = Offset(minWidth / 2 + indicatorHorizontalPadding, indicatorVerticalPadding); if (minWidth < _NavigationRailDefaultsM2(context).minWidth!) { indicatorOffset = Offset(minWidth / 2 + _horizontalDestinationSpacingM3, indicatorVerticalPadding); } content = Container( constraints: BoxConstraints( minWidth: minWidth, minHeight: minHeight, ), padding: padding ?? const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), child: ClipRect( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ topSpacing, _AddIndicator( addIndicator: useIndicator, indicatorColor: indicatorColor, indicatorShape: indicatorShape, isCircular: false, indicatorAnimation: destinationAnimation, child: themedIcon, ), labelSpacing, Align( alignment: Alignment.topCenter, heightFactor: appearingAnimationValue, widthFactor: 1.0, child: FadeTransition( alwaysIncludeSemantics: true, opacity: labelFadeAnimation, child: styledLabel, ), ), bottomSpacing, ], ), ), ); break; case NavigationRailLabelType.all: final double minHeight = material3 ? 0 : minWidth; final Widget topSpacing = SizedBox(height: material3 ? 0 : _verticalDestinationPaddingWithLabel); final Widget labelSpacing = SizedBox(height: material3 ? _verticalIconLabelSpacingM3 : 0); final Widget bottomSpacing = SizedBox(height: material3 ? _verticalDestinationSpacingM3 : _verticalDestinationPaddingWithLabel); final double indicatorHorizontalPadding = (destionationPadding.left / 2) - (destionationPadding.right / 2); final double indicatorVerticalPadding = destionationPadding.top; indicatorOffset = Offset(minWidth / 2 + indicatorHorizontalPadding, indicatorVerticalPadding); if (minWidth < _NavigationRailDefaultsM2(context).minWidth!) { indicatorOffset = Offset(minWidth / 2 + _horizontalDestinationSpacingM3, indicatorVerticalPadding); } content = Container( constraints: BoxConstraints( minWidth: minWidth, minHeight: minHeight, ), padding: padding ?? const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), child: Column( children: [ topSpacing, _AddIndicator( addIndicator: useIndicator, indicatorColor: indicatorColor, indicatorShape: indicatorShape, isCircular: false, indicatorAnimation: destinationAnimation, child: themedIcon, ), labelSpacing, styledLabel, bottomSpacing, ], ), ); break; } final ColorScheme colors = Theme.of(context).colorScheme; return Semantics( container: true, selected: selected, child: Stack( children: [ Material( type: MaterialType.transparency, child: _IndicatorInkWell( onTap: onTap, borderRadius: BorderRadius.all(Radius.circular(minWidth / 2.0)), customBorder: indicatorShape, splashColor: colors.primary.withOpacity(0.12), hoverColor: colors.primary.withOpacity(0.04), useMaterial3: material3, indicatorOffset: indicatorOffset, child: content, ), ), Semantics( label: indexLabel, ), ], ), ); } } class _IndicatorInkWell extends InkResponse { const _IndicatorInkWell({ super.child, super.onTap, ShapeBorder? customBorder, BorderRadius? borderRadius, super.splashColor, super.hoverColor, required this.useMaterial3, required this.indicatorOffset, }) : super( containedInkWell: true, highlightShape: BoxShape.rectangle, borderRadius: useMaterial3 ? null : borderRadius, customBorder: useMaterial3 ? customBorder : null, ); final Offset indicatorOffset; final bool useMaterial3; @override RectCallback? getRectCallback(RenderBox referenceBox) { if (useMaterial3) { return () { return Rect.fromLTWH( indicatorOffset.dx - (_kCircularIndicatorDiameter / 2), indicatorOffset.dy, _kCircularIndicatorDiameter, _kIndicatorHeight, ); }; } return null; } } /// When [addIndicator] is `true`, puts [child] center aligned in a [Stack] with /// a [NavigationIndicator] behind it, otherwise returns [child]. /// /// When [isCircular] is true, the indicator will be a circle, otherwise the /// indicator will be a stadium shape. class _AddIndicator extends StatelessWidget { const _AddIndicator({ required this.addIndicator, required this.isCircular, required this.indicatorColor, required this.indicatorShape, required this.indicatorAnimation, required this.child, }); final bool addIndicator; final Widget child; final Animation indicatorAnimation; final Color? indicatorColor; final ShapeBorder? indicatorShape; final bool isCircular; @override Widget build(BuildContext context) { if (!addIndicator) { return child; } late final Widget indicator; if (isCircular) { indicator = NavigationIndicator( animation: indicatorAnimation, height: _kCircularIndicatorDiameter, width: _kCircularIndicatorDiameter, borderRadius: BorderRadius.circular(_kCircularIndicatorDiameter / 2), color: indicatorColor, ); } else { indicator = NavigationIndicator( animation: indicatorAnimation, width: _kCircularIndicatorDiameter, shape: indicatorShape, color: indicatorColor, ); } return Stack( alignment: Alignment.center, children: [ indicator, child, ], ); } } /// Defines the behavior of the labels of a [NavigationRail]. /// /// See also: /// /// * [NavigationRail] enum NavigationRailLabelType { /// Only the [NavigationRailDestination]s are shown. none, /// Only the selected [NavigationRailDestination] will show its label. /// /// The label will animate in and out as new [NavigationRailDestination]s are /// selected. selected, /// All [NavigationRailDestination]s will show their label. all, } /// Defines a [NavigationRail] button that represents one "destination" view. /// /// See also: /// /// * [NavigationRail] class NavigationRailDestination { /// Creates a destination that is used with [NavigationRail.destinations]. /// /// [icon] and [label] must be non-null. When the [NavigationRail.labelType] /// is [NavigationRailLabelType.none], the label is still used for semantics, /// and may still be used if [NavigationRail.extended] is true. const NavigationRailDestination({ required this.icon, Widget? selectedIcon, required this.label, this.padding, }) : selectedIcon = selectedIcon ?? icon, assert(icon != null), assert(label != null); /// The icon of the destination. /// /// Typically the icon is an [Icon] or an [ImageIcon] widget. If another type /// of widget is provided then it should configure itself to match the current /// [IconTheme] size and color. /// /// If [selectedIcon] is provided, this will only be displayed when the /// destination is not selected. /// /// To make the [NavigationRail] more accessible, consider choosing an /// icon with a stroked and filled version, such as [Icons.cloud] and /// [Icons.cloud_queue]. The [icon] should be set to the stroked version and /// [selectedIcon] to the filled version. final Widget icon; /// The label for the destination. /// /// The label must be provided when used with the [NavigationRail]. When the /// [NavigationRail.labelType] is [NavigationRailLabelType.none], the label is /// still used for semantics, and may still be used if /// [NavigationRail.extended] is true. final Widget label; /// The amount of space to inset the destination item. final EdgeInsetsGeometry? padding; /// An alternative icon displayed when this destination is selected. /// /// If this icon is not provided, the [NavigationRail] will display [icon] in /// either state. The size, color, and opacity of the /// [NavigationRail.selectedIconTheme] will still apply. /// /// See also: /// /// * [NavigationRailDestination.icon], for a description of how to pair /// icons. final Widget selectedIcon; } class _ExtendedNavigationRailAnimation extends InheritedWidget { const _ExtendedNavigationRailAnimation({ required this.animation, required super.child, }) : assert(child != null); final Animation animation; @override bool updateShouldNotify(_ExtendedNavigationRailAnimation old) => animation != old.animation; } // There don't appear to be tokens for these values, but they are // shown in the spec. const double _horizontalDestinationPadding = 8.0; const double _verticalDestinationPaddingNoLabel = 24.0; const double _verticalDestinationPaddingWithLabel = 16.0; const Widget _verticalSpacer = SizedBox(height: 8.0); const double _verticalIconLabelSpacingM3 = 4.0; const double _verticalDestinationSpacingM3 = 12.0; const double _horizontalDestinationSpacingM3 = 12.0; // Hand coded defaults based on Material Design 2. class _NavigationRailDefaultsM2 extends NavigationRailThemeData { _NavigationRailDefaultsM2(BuildContext context) : _theme = Theme.of(context), _colors = Theme.of(context).colorScheme, super( elevation: 0, groupAlignment: -1, labelType: NavigationRailLabelType.none, useIndicator: false, minWidth: 72.0, minExtendedWidth: 256, ); final ColorScheme _colors; final ThemeData _theme; @override Color? get backgroundColor => _colors.surface; @override IconThemeData? get selectedIconTheme { return IconThemeData( size: 24.0, color: _colors.primary, opacity: 1.0, ); } @override TextStyle? get selectedLabelTextStyle { return _theme.textTheme.bodyLarge!.copyWith(color: _colors.primary); } @override IconThemeData? get unselectedIconTheme { return IconThemeData( size: 24.0, color: _colors.onSurface, opacity: 0.64, ); } @override TextStyle? get unselectedLabelTextStyle { return _theme.textTheme.bodyLarge!.copyWith(color: _colors.onSurface.withOpacity(0.64)); } } // BEGIN GENERATED TOKEN PROPERTIES - NavigationRail // Do not edit by hand. The code between the "BEGIN GENERATED" and // "END GENERATED" comments are generated from data in the Material // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. // Token database version: v0_143 class _NavigationRailDefaultsM3 extends NavigationRailThemeData { _NavigationRailDefaultsM3(this.context) : super( elevation: 0.0, groupAlignment: -1, labelType: NavigationRailLabelType.none, useIndicator: true, minWidth: 80.0, minExtendedWidth: 256, ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color? get backgroundColor => _colors.surface; @override Color? get indicatorColor => _colors.secondaryContainer; @override ShapeBorder? get indicatorShape => const StadiumBorder(); @override IconThemeData? get selectedIconTheme { return IconThemeData( size: 24.0, color: _colors.onSecondaryContainer, ); } @override TextStyle? get selectedLabelTextStyle { return _textTheme.labelMedium!.copyWith(color: _colors.onSurface); } @override IconThemeData? get unselectedIconTheme { return IconThemeData( size: 24.0, color: _colors.onSurfaceVariant, ); } @override TextStyle? get unselectedLabelTextStyle { return _textTheme.labelMedium!.copyWith(color: _colors.onSurface); } } // END GENERATED TOKEN PROPERTIES - NavigationRail ```

In your App you have to specify those values now, you can change the colors of course:

example usage in your code ``` AdaptiveScaffold( backgroundColor: Colors.transparent, selectedIconTheme: IconThemeData(color: Colors.black), unselectedIconTheme: IconThemeData(color: Colors.black), selectedLabelTextStyle: TextStyle(color: Colors.black) ... ```

(If I did some formatting wrong please excuse me, this is one of my first github comments... )

martijn00 commented 1 month ago

Same here as: https://github.com/flutter/flutter/issues/120963

@stuartmorgan @gspencergoog I believe this is already fixed. See https://github.com/flutter/packages/blob/main/packages/flutter_adaptive_scaffold/lib/src/adaptive_scaffold.dart#L513

The theme is passed through and parameters have been made nullable.

gspencergoog commented 1 month ago

Closing as fixed.

github-actions[bot] commented 1 month ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.