Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elevation issue with Material widget, when opting in on useMaterial3 causes widespread elevation issues #107190

Closed
rydmike opened this issue Jul 6, 2022 · 3 comments · Fixed by #110624
Assignees
Labels
c: proposal A detailed proposal for a change to Flutter customer: crowd Affects or could affect many people, though not necessarily a specific customer. f: material design flutter/packages/flutter/material repository. framework flutter/packages/flutter repository. See also f: labels. r: fixed Issue is closed as already fixed in a newer version

Comments

@rydmike
Copy link
Contributor

rydmike commented Jul 6, 2022

Steps to Reproduce

When opting in on ThemeData.useMaterial3 there is no elevation effect of Material unless its shadowColor and/or surfaceTintColor is also specified.

When using M2 the elevation effect comes from specifying only elevation of Material, this is however no longer the case when using M3 and Material.

The impact of this Material behaviour change are:

  • Material gets no elevation of any kind, even if elevation has been specified.
  • When migrating to M3, custom widgets using Material will not get elevated, unless additional shadowColor and/or surfaceTintColor are added during migration, this causes extra migration friction.
  • When using M3, Flutter SDK widgets that have not yet been migrated to support M3 and that depend on the underlying Material widget and use elevation, will not get any elevation at all and cannot be elevated even if so specified. Some current such examples are:
    • Drawer
    • PopupMenuButton
    • BottomNavigationBar
    • NavigationRail
    • Dialog
    • AlertDialog
    • TimePickerDialog
    • DatePickerDialog
    • MaterialBanner
    • BottomSheet

When using Material directly, the elevation issue can of course be addressed in M3 mode by adding any desired shadowColor and/or surfaceTintColor to it, but it is still two extra properties that were not needed before to elevate surfaces.

For the Flutter SDK widgets using Material and elevation, the used underlying Material’s shadowColor and/or surfaceTintColor are not exposed by such widgets or their themes. There is thus no easy fix for them to make them elevated again. The only currently available fix, when opting on M3, is to wrap widgets that are “elevation broken” when useMaterial3 is true, with a copy of the effective theme, where useMaterial3 is set to false. This is a rather tedious workaround and fix.

Developers have been struggling with this, some examples include:

Potential and Proposed Fix

Please consider changing Material default behaviour when useMaterial3 is true so that it uses theme colorScheme.shadow for shadowColor, and colorScheme.surfaceTint for surfaceTintColor as defaults.

This would make M3 mode Material get M3 style elevation (shadow and tint) by default when specifying only elevation, as before when using Material. Flutter SDK widgets that have not yet been migrated to support M3 internally, would then get M3 style tinted elevation with shadow, when only elevation is used. Such Flutter SDK widgets can then later implement their own more correct M3 elevation design, be it no elevation, shadow or tint only based elevation.

This default would also make migrating custom widgets using Material easier, since they would still get elevation in M3, using both tint and shadow by default, as mostly expected, without need to specify them explicitly. This would result in less surprises with flat custom widgets using Material and elevation, where devs expect them to continue to be elevated. I foresee a lot of issues, or at least questions, when migrating custom widgets to M3, that use Material and elevation with its current behaviour.

This proposal has its own challenges, I’m aware. Maybe you can come up with something that works even better.

An alternative solution might be to add a MaterialTheme where one could specify the shadowColor and surfaceTintColor for Material and thus there give it the props globally for the app, to give Material elevation in M3 as well when only elevation is specified at widget level.

Since the full migration of all widgets to support M3 is understandably a long journey, the transition period is currently causing frustration among early M3 adopters. The Material widget is at the root of many of them, if it had better backwards default behaviour in M3, most issues could be avoided, and widgets not using M3 design yet, can be made more M3 like with current M2 theming capabilities.

Why is a Fix Needed?

Eventually all widgets will be migrated to support M3. This issue has previously been closed with that as a reference comment. This is true, eventually all above widgets will support elevation, and hopefully also expose shadow and tint colors as both widget and theme properties. But it is not likely that the M3 implementation for all widgets with this issue will arrive very soon.

The fact that there are no more widgets implemented that would support and fix its elevation issue in M3, in latest master channel, compared to stable 3.0.4, implies that M3 support for any of the widgets with this issue might not even be landing in next stable release. This further underlines why some kind of urgent and/or intermediate fix for the underlying Material widget is needed when useMaterial3 is set to true.

As also demonstrated in this issue, the Material elevation issue with M3 is much more widespread than previously reported, and very troublesome or close to impossible to work around. This makes early adoption of M3 in Flutter a less than pleasant experience.

Current design will also require extra work to migrate custom/composed widgets to M3 that are based on Material, which is a very common building block. This will further increase migration friction and slow down its adoption in existing applications.

Issue Demo App

In the issue demo app, we can see examples of Flutter SDK widgets that get no elevation when switching to M3. The demo app can switch dynamically between M2 and M3 theme. In addition to the demo theme colors. It only includes the above listed widget as examples, that currently are known to have the Material M3 based elevation issue. There might be more widgets using Material not included here that exhibit the same issue.

The issue demo app is available in DartPad for convenience here: https://dartpad.dev/?id=c927904ebd995dd849efc0e7ac958630

The live DartPad example uses Flutter stable 3.0.4, but the issue and results are the same on latest Flutter master 3.1.0-0.0.pre.1515.

Issue Demo App Source Code
// MIT License
//
// Copyright (c) 2022 Mike Rydstrom
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import 'package:flutter/material.dart';

// Light M3 ColorScheme.
const ColorScheme mySchemeLight = ColorScheme(
  brightness: Brightness.light,
  primary: Color(0xff386a20),
  onPrimary: Color(0xffffffff),
  primaryContainer: Color(0xffc0f0a4),
  onPrimaryContainer: Color(0xff042100),
  secondary: Color(0xff55624c),
  onSecondary: Color(0xffffffff),
  secondaryContainer: Color(0xffd9e7cb),
  onSecondaryContainer: Color(0xff131f0d),
  tertiary: Color(0xff386667),
  onTertiary: Color(0xffffffff),
  tertiaryContainer: Color(0xffbbebeb),
  onTertiaryContainer: Color(0xff002021),
  error: Color(0xffba1b1b),
  onError: Color(0xffffffff),
  errorContainer: Color(0xffffdad4),
  onErrorContainer: Color(0xff410001),
  outline: Color(0xff74796e),
  background: Color(0xfffdfdf6),
  onBackground: Color(0xff1a1c18),
  surface: Color(0xfffdfdf6),
  onSurface: Color(0xff1a1c18),
  surfaceVariant: Color(0xffdfe4d6),
  onSurfaceVariant: Color(0xff43493e),
  inverseSurface: Color(0xff2f312c),
  onInverseSurface: Color(0xfff1f1ea),
  inversePrimary: Color(0xff9cd67d),
  shadow: Color(0xff000000),
  surfaceTint: Color(0xff386a20),
);

// Dark M3 ColorScheme.
const ColorScheme mySchemeDark = ColorScheme(
  brightness: Brightness.dark,
  primary: Color(0xff9cd67d),
  onPrimary: Color(0xff0c3900),
  primaryContainer: Color(0xff205107),
  onPrimaryContainer: Color(0xffc0f0a4),
  secondary: Color(0xffbdcbb0),
  onSecondary: Color(0xff273420),
  secondaryContainer: Color(0xff3e4a36),
  onSecondaryContainer: Color(0xffd9e7cb),
  tertiary: Color(0xffa0cfcf),
  onTertiary: Color(0xff003738),
  tertiaryContainer: Color(0xff1e4e4e),
  onTertiaryContainer: Color(0xffbbebeb),
  error: Color(0xffffb4a9),
  onError: Color(0xff680003),
  errorContainer: Color(0xff930006),
  onErrorContainer: Color(0xffffb4a9),
  outline: Color(0xff8d9286),
  background: Color(0xff1a1c18),
  onBackground: Color(0xffe3e3dc),
  surface: Color(0xff1a1c18),
  onSurface: Color(0xffe3e3dc),
  surfaceVariant: Color(0xff43493e),
  onSurfaceVariant: Color(0xffc4c8bb),
  inverseSurface: Color(0xffe3e3dc),
  onInverseSurface: Color(0xff2f312c),
  inversePrimary: Color(0xff386a20),
  shadow: Color(0xff000000),
  surfaceTint: Color(0xff9cd67d),
);

// Example theme -
ThemeData demoTheme(Brightness mode, bool useMaterial3) =>
    mode == Brightness.light
        ? ThemeData(
            colorScheme: mySchemeLight,
            toggleableActiveColor:
                useMaterial3 ? mySchemeLight.primary : mySchemeLight.secondary,
            primaryColor: mySchemeLight.primary,
            primaryColorLight: Color.alphaBlend(
                Colors.white.withAlpha(0x66), mySchemeLight.primary),
            primaryColorDark: Color.alphaBlend(
                Colors.black.withAlpha(0x66), mySchemeLight.primary),
            secondaryHeaderColor: Color.alphaBlend(
                Colors.white.withAlpha(0xCC), mySchemeLight.primary),
            scaffoldBackgroundColor: mySchemeLight.background,
            canvasColor: mySchemeLight.background,
            backgroundColor: mySchemeLight.background,
            cardColor: mySchemeLight.surface,
            bottomAppBarColor: mySchemeLight.surface,
            dialogBackgroundColor: mySchemeLight.surface,
            indicatorColor: mySchemeLight.onPrimary,
            dividerColor: mySchemeLight.onSurface.withOpacity(0.12),
            errorColor: mySchemeLight.error,
            applyElevationOverlayColor: false,
            useMaterial3: useMaterial3,
            visualDensity: VisualDensity.standard,
          )
        : ThemeData(
            colorScheme: mySchemeDark,
            toggleableActiveColor:
                useMaterial3 ? mySchemeDark.primary : mySchemeDark.secondary,
            primaryColor: mySchemeDark.primary,
            primaryColorLight: Color.alphaBlend(
                Colors.white.withAlpha(0x59), mySchemeDark.primary),
            primaryColorDark: Color.alphaBlend(
                Colors.black.withAlpha(0x72), mySchemeDark.primary),
            secondaryHeaderColor: Color.alphaBlend(
                Colors.black.withAlpha(0x99), mySchemeDark.primary),
            scaffoldBackgroundColor: mySchemeDark.background,
            canvasColor: mySchemeDark.background,
            backgroundColor: mySchemeDark.background,
            cardColor: mySchemeDark.surface,
            bottomAppBarColor: mySchemeDark.surface,
            dialogBackgroundColor: mySchemeDark.surface,
            indicatorColor: mySchemeDark.onBackground,
            dividerColor: mySchemeDark.onSurface.withOpacity(0.12),
            errorColor: mySchemeDark.error,
            applyElevationOverlayColor: true,
            useMaterial3: useMaterial3,
            visualDensity: VisualDensity.standard,
          );

void main() {
  runApp(const ThemeRoadsApp());
}

class ThemeRoadsApp extends StatefulWidget {
  const ThemeRoadsApp({super.key});

  @override
  State<ThemeRoadsApp> createState() => _ThemeRoadsAppState();
}

class _ThemeRoadsAppState extends State<ThemeRoadsApp> {
  bool useMaterial3 = false;
  ThemeMode themeMode = ThemeMode.light;
  // ThemingWay themingWay = ThemingWay.road10;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      themeMode: themeMode,
      theme: demoTheme(Brightness.light, useMaterial3),
      darkTheme: demoTheme(Brightness.dark, useMaterial3),
      home: Scaffold(
        appBar: AppBar(
          title: const Text(('M3 Elevation Issue')),
          actions: [
            IconButton(
              icon: useMaterial3
                  ? const Icon(Icons.filter_3)
                  : const Icon(Icons.filter_2),
              onPressed: () {
                setState(() {
                  useMaterial3 = !useMaterial3;
                });
              },
              tooltip: "Switch to Material ${useMaterial3 ? 2 : 3}",
            ),
            IconButton(
              icon: themeMode == ThemeMode.dark
                  ? const Icon(Icons.wb_sunny_outlined)
                  : const Icon(Icons.wb_sunny),
              onPressed: () {
                setState(() {
                  if (themeMode == ThemeMode.light) {
                    themeMode = ThemeMode.dark;
                  } else {
                    themeMode = ThemeMode.light;
                  }
                });
              },
              tooltip: "Toggle brightness",
            ),
          ],
        ),
        body: const HomePage(),
        drawer: const Drawer(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    final String materialType =
        Theme.of(context).useMaterial3 ? "Material 3" : "Material 2";
    return ListView(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      children: [
        const SizedBox(height: 8),
        Text(
          'Theme Demo - $materialType',
          style: Theme.of(context).textTheme.headlineSmall,
        ),
        const Divider(),
        const ShowColorSchemeColors(),
        const Divider(),
        const ShowThemeDataColors(),
        const Divider(),
        const ThemeShowcase(),
      ],
    );
  }
}

/// Theme showcase for the current theme to show M3 elevation issues.
class ThemeShowcase extends StatelessWidget {
  const ThemeShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: const <Widget>[
        PopupMenuShowcase(),
        SizedBox(height: 8),
        Divider(),
        BottomNavigationBarShowcase(),
        SizedBox(height: 8),
        Divider(),
        NavigationBarShowcase(),
        SizedBox(height: 8),
        Divider(),
        NavigationRailShowcase(),
        SizedBox(height: 8),
        Divider(),
        AlertDialogShowcase(),
        TimePickerDialogShowcase(),
        DatePickerDialogShowcase(),
        Divider(),
        MaterialAndBottomSheetShowcase(),
        Divider(height: 32),
        SizedBox(height: 8),
      ],
    );
  }
}

class PopupMenuShowcase extends StatelessWidget {
  const PopupMenuShowcase({
    super.key,
    this.enabled = true,
    this.popupRadius,
  });
  final bool enabled;
  final double? popupRadius;

  @override
  Widget build(BuildContext context) {
    return Wrap(
      crossAxisAlignment: WrapCrossAlignment.center,
      spacing: 8,
      runSpacing: 4,
      children: <Widget>[
        _PopupMenuButton(enabled: enabled, radius: popupRadius),
      ],
    );
  }
}

class _PopupMenuButton extends StatelessWidget {
  const _PopupMenuButton({
    this.enabled = true,
    this.radius,
  });
  final bool enabled;
  final double? radius;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final ColorScheme scheme = theme.colorScheme;
    return PopupMenuButton<int>(
      onSelected: (_) {},
      enabled: enabled,
      tooltip: enabled ? 'Show menu' : 'Menu disabled',
      itemBuilder: (BuildContext context) => const <PopupMenuItem<int>>[
        PopupMenuItem<int>(value: 1, child: Text('Option 1')),
        PopupMenuItem<int>(value: 2, child: Text('Option 2')),
        PopupMenuItem<int>(value: 3, child: Text('Option 3')),
        PopupMenuItem<int>(value: 4, child: Text('Option 4')),
        PopupMenuItem<int>(value: 5, child: Text('Option 5')),
      ],
      child: AbsorbPointer(
        child: ElevatedButton.icon(
          style: ElevatedButton.styleFrom(
            elevation: 0,
            primary: scheme.secondary,
            onPrimary: scheme.onSecondary,
            onSurface: scheme.onSurface,
            shape: radius != null
                ? RoundedRectangleBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(radius ?? 4)),
                  )
                : null,
          ),
          onPressed: enabled ? () {} : null,
          icon: const Icon(Icons.expand_more_outlined),
          label: const Text('PopupMenu'),
        ),
      ),
    );
  }
}

class BottomNavigationBarShowcase extends StatefulWidget {
  const BottomNavigationBarShowcase({super.key});

  @override
  State<BottomNavigationBarShowcase> createState() =>
      _BottomNavigationBarShowcaseState();
}

class _BottomNavigationBarShowcaseState
    extends State<BottomNavigationBarShowcase> {
  int buttonIndex = 0;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final TextStyle denseHeader =
        theme.textTheme.titleMedium!.copyWith(fontSize: 13);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        MediaQuery.removePadding(
          context: context,
          removeBottom: true,
          child: BottomNavigationBar(
            currentIndex: buttonIndex,
            onTap: (int value) {
              setState(() {
                buttonIndex = value;
              });
            },
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                icon: Icon(Icons.chat_bubble),
                label: 'Chat',
                // title: Text('Item 1'),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.beenhere),
                label: 'Tasks',
                // title: Text('Item 2'),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.create_new_folder),
                label: 'Folder',
                // title: Text('Item 3'),
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
          child: Text(
            'BottomNavigationBar (Material 2 Design)',
            style: denseHeader,
          ),
        ),
      ],
    );
  }
}

class NavigationBarShowcase extends StatefulWidget {
  const NavigationBarShowcase({super.key});

  @override
  State<NavigationBarShowcase> createState() => _NavigationBarShowcaseState();
}

class _NavigationBarShowcaseState extends State<NavigationBarShowcase> {
  int buttonIndex = 0;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final TextStyle denseHeader =
        theme.textTheme.titleMedium!.copyWith(fontSize: 13);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        MediaQuery.removePadding(
          context: context,
          removeBottom: true,
          child: NavigationBar(
            selectedIndex: buttonIndex,
            onDestinationSelected: (int value) {
              setState(() {
                buttonIndex = value;
              });
            },
            destinations: const <NavigationDestination>[
              NavigationDestination(
                icon: Icon(Icons.chat_bubble),
                label: 'Chat',
              ),
              NavigationDestination(
                icon: Icon(Icons.beenhere),
                label: 'Tasks',
              ),
              NavigationDestination(
                icon: Icon(Icons.create_new_folder),
                label: 'Folder',
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
          child: Text(
            'NavigationBar (Material 3 Design)',
            style: denseHeader,
          ),
        ),
      ],
    );
  }
}

class NavigationRailShowcase extends StatefulWidget {
  const NavigationRailShowcase({
    super.key,
    this.child,
    this.height = 350,
  });

  /// A child widget that we can use to place controls on the
  /// side of the NavigationRail in the show case widget.
  final Widget? child;

  /// The vertical space for the navigation bar.
  final double height;

  @override
  State<NavigationRailShowcase> createState() => _NavigationRailShowcaseState();
}

class _NavigationRailShowcaseState extends State<NavigationRailShowcase> {
  int buttonIndex = 0;
  bool isExtended = false;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final TextStyle denseHeader = theme.textTheme.titleMedium!.copyWith(
      fontSize: 13,
    );
    final TextStyle denseBody = theme.textTheme.bodyMedium!
        .copyWith(fontSize: 12, color: theme.textTheme.bodySmall!.color);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
          child: Text(
            'NavigationRail',
            style: denseHeader,
          ),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
          child: Text(
            'Default SDK background color is theme.colorScheme.surface.',
            style: denseBody,
          ),
        ),
        const Divider(height: 1),
        SizedBox(
          height: widget.height,
          // If we expand the rail and have a very narrow screen, it will
          // take up a lot of height, more than we want to give to the demo
          // panel, just let it overflow then. This may happen when we place
          // a lot of widgets in the child that no longer fits on a phone
          // with expanded rail.
          child: ClipRect(
            child: OverflowBox(
              alignment: AlignmentDirectional.topStart,
              maxHeight: 1200,
              child: Row(
                children: <Widget>[
                  NavigationRail(
                    elevation: 4,
                    extended: isExtended,
                    minExtendedWidth: 150,
                    labelType: isExtended ? NavigationRailLabelType.none : null,
                    selectedIndex: buttonIndex,
                    onDestinationSelected: (int value) {
                      setState(() {
                        buttonIndex = value;
                      });
                    },
                    destinations: const <NavigationRailDestination>[
                      NavigationRailDestination(
                        icon: Icon(Icons.chat_bubble),
                        label: Text('Chat'),
                      ),
                      NavigationRailDestination(
                        icon: Icon(Icons.beenhere),
                        label: Text('Tasks'),
                      ),
                      NavigationRailDestination(
                        icon: Icon(Icons.create_new_folder),
                        label: Text('Folder'),
                      ),
                      NavigationRailDestination(
                        icon: Icon(Icons.logout),
                        label: Text('Logout'),
                      ),
                    ],
                  ),
                  const VerticalDivider(width: 1),
                  Expanded(
                    child: Column(
                      children: <Widget>[
                        SwitchListTile(
                          title: const Text('Expand and collapse'),
                          subtitle: const Text('ON to expand  OFF to collapse\n'
                              'Only used for local control of Rail '
                              'presentation.'),
                          value: isExtended,
                          onChanged: (bool value) {
                            setState(() {
                              isExtended = value;
                            });
                          },
                        ),
                        widget.child ?? const SizedBox.shrink(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class AlertDialogShowcase extends StatelessWidget {
  const AlertDialogShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Allow location services'),
      content: const Text('Let us help determine location. This means '
          'sending anonymous location data to us'),
      actions: <Widget>[
        TextButton(onPressed: () {}, child: const Text('CANCEL')),
        TextButton(onPressed: () {}, child: const Text('ALLOW')),
      ],
      actionsPadding: const EdgeInsets.symmetric(horizontal: 16),
    );
  }
}

class TimePickerDialogShowcase extends StatelessWidget {
  const TimePickerDialogShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    // The TimePickerDialog pops the context with its buttons, clicking them
    // pops the page when not used in a showDialog. We just need to see it, no
    // need to use it to visually see what it looks like, so absorbing pointers.
    return AbsorbPointer(
      child: TimePickerDialog(
        initialTime: TimeOfDay.now(),
      ),
    );
  }
}

class DatePickerDialogShowcase extends StatelessWidget {
  const DatePickerDialogShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    // The DatePickerDialog pops the context with its buttons, clicking them
    // pops the page when not used in a showDialog. We just need to see it, no
    // need to use it to visually see what it looks like, so absorbing pointers.
    return AbsorbPointer(
      child: DatePickerDialog(
        initialDate: DateTime.now(),
        firstDate: DateTime(1930),
        lastDate: DateTime(2050),
      ),
    );
  }
}

class MaterialAndBottomSheetShowcase extends StatelessWidget {
  const MaterialAndBottomSheetShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final ColorScheme colorScheme = theme.colorScheme;
    final bool isLight = theme.brightness == Brightness.light;

    final Color defaultBackgroundColor = isLight
        ? Color.alphaBlend(
            colorScheme.onSurface.withOpacity(0.80), colorScheme.surface)
        : colorScheme.onSurface;
    final Color snackBackground =
        theme.snackBarTheme.backgroundColor ?? defaultBackgroundColor;
    final Color snackForeground =
        ThemeData.estimateBrightnessForColor(snackBackground) ==
                Brightness.light
            ? Colors.black
            : Colors.white;
    final TextStyle snackStyle = theme.snackBarTheme.contentTextStyle ??
        ThemeData(brightness: Brightness.light)
            .textTheme
            .titleMedium!
            .copyWith(color: snackForeground);
    final TextStyle denseHeader = theme.textTheme.titleMedium!.copyWith(
      fontSize: 13,
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        MaterialBanner(
          elevation: 3,
          padding: const EdgeInsets.all(20),
          content: const Text('Hello, I am a Material Banner'),
          leading: const Icon(Icons.agriculture_outlined),
          actions: <Widget>[
            TextButton(
              child: const Text('OPEN'),
              onPressed: () {},
            ),
            TextButton(
              child: const Text('DISMISS'),
              onPressed: () {},
            ),
          ],
        ),
        const SizedBox(height: 12),
        Text('Material type canvas', style: denseHeader),
        const Material(
          elevation: 0,
          child: SizedBox(
            height: 50,
            child: Center(child: Text('Material type canvas, elevation 0')),
          ),
        ),
        const SizedBox(height: 10),
        const Material(
          elevation: 1,
          child: SizedBox(
            height: 50,
            child: Center(child: Text('Material type canvas, elevation 1')),
          ),
        ),
        const SizedBox(height: 10),
        const Material(
          elevation: 4,
          child: SizedBox(
            height: 50,
            child: Center(child: Text('Material type canvas, elevation 4')),
          ),
        ),
        const SizedBox(height: 24),
        Material(
          elevation: 0,
          shadowColor: theme.colorScheme.shadow,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation 0, with shadow color')),
          ),
        ),
        const SizedBox(height: 10),
        Material(
          elevation: 1,
          shadowColor: theme.colorScheme.shadow,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation 1, with shadow color')),
          ),
        ),
        const SizedBox(height: 10),
        Material(
          elevation: 4,
          shadowColor: theme.colorScheme.shadow,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation 4, with shadow color')),
          ),
        ),
        const SizedBox(height: 24),
        Material(
          elevation: 0,
          shadowColor: theme.colorScheme.shadow,
          surfaceTintColor: theme.colorScheme.surfaceTint,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation 0, with shadow and tint color')),
          ),
        ),
        const SizedBox(height: 10),
        Material(
          elevation: 1,
          shadowColor: theme.colorScheme.shadow,
          surfaceTintColor: theme.colorScheme.surfaceTint,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation 1, with shadow and tint color')),
          ),
        ),
        const SizedBox(height: 10),
        Material(
          elevation: 4,
          shadowColor: theme.colorScheme.shadow,
          surfaceTintColor: theme.colorScheme.surfaceTint,
          child: const SizedBox(
            height: 50,
            child: Center(
                child: Text(
                    'Material type canvas, elevation, with shadow and tint color')),
          ),
        ),
        const SizedBox(height: 24),
        AbsorbPointer(
          child: BottomSheet(
            elevation: 8,
            enableDrag: false,
            onClosing: () {},
            builder: (final BuildContext context) => SizedBox(
              height: 150,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const SizedBox(height: 20),
                    Text(
                      'A Material BottomSheet',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    Text(
                      'Like Drawer it uses Material of type canvas as '
                      'background.',
                      style: Theme.of(context).textTheme.bodySmall,
                      textAlign: TextAlign.center,
                    ),
                    const Spacer(),
                    Material(
                      color: snackBackground,
                      elevation: 0,
                      child: SizedBox(
                        height: 40,
                        child: Center(
                          child: Text(
                              'A Material SnackBar, style simulation only',
                              style: snackStyle),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class TextThemeShowcase extends StatelessWidget {
  const TextThemeShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    return TextThemeColumnShowcase(textTheme: Theme.of(context).textTheme);
  }
}

class PrimaryTextThemeShowcase extends StatelessWidget {
  const PrimaryTextThemeShowcase({super.key});

  @override
  Widget build(BuildContext context) {
    return TextThemeColumnShowcase(
        textTheme: Theme.of(context).primaryTextTheme);
  }
}

class TextThemeColumnShowcase extends StatelessWidget {
  const TextThemeColumnShowcase({super.key, required this.textTheme});
  final TextTheme textTheme;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text('Font: ${textTheme.titleSmall!.fontFamily}',
            style:
                textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600)),
        Text(
          'Display Large '
          '(${textTheme.displayLarge!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.displayLarge,
        ),
        Text(
          'Display Medium '
          '(${textTheme.displayMedium!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.displayMedium,
        ),
        Text(
          'Display Small '
          '(${textTheme.displaySmall!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.displaySmall,
        ),
        const SizedBox(height: 12),
        Text(
          'Headline Large '
          '(${textTheme.headlineLarge!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.headlineLarge,
        ),
        Text(
          'Headline Medium '
          '(${textTheme.headlineMedium!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.headlineMedium,
        ),
        Text(
          'Headline Small '
          '(${textTheme.headlineSmall!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.headlineSmall,
        ),
        const SizedBox(height: 12),
        Text(
          'Title Large '
          '(${textTheme.titleLarge!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.titleLarge,
        ),
        Text(
          'Title Medium '
          '(${textTheme.titleMedium!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.titleMedium,
        ),
        Text(
          'Title Small '
          '(${textTheme.titleSmall!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.titleSmall,
        ),
        const SizedBox(height: 12),
        Text(
          'Body Large '
          '(${textTheme.bodyLarge!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.bodyLarge,
        ),
        Text(
          'Body Medium '
          '(${textTheme.bodyMedium!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.bodyMedium,
        ),
        Text(
          'Body Small '
          '(${textTheme.bodySmall!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.bodySmall,
        ),
        const SizedBox(height: 12),
        Text(
          'Label Large '
          '(${textTheme.labelLarge!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.labelLarge,
        ),
        Text(
          'Label Medium '
          '(${textTheme.labelMedium!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.labelMedium,
        ),
        Text(
          'Label Small '
          '(${textTheme.labelSmall!.fontSize!.toStringAsFixed(0)})',
          style: textTheme.labelSmall,
        ),
      ],
    );
  }
}

/// Draw a number of boxes showing the colors of key theme color properties
/// in the ColorScheme of the inherited ThemeData and its color properties.
class ShowColorSchemeColors extends StatelessWidget {
  const ShowColorSchemeColors({super.key, this.onBackgroundColor});

  /// The color of the background the color widget are being drawn on.
  ///
  /// Some of the theme colors may have semi transparent fill color. To compute
  /// a legible text color for the sum when it shown on a background color, we
  /// need to alpha merge it with background and we need the exact background
  /// color it is drawn on for that. If not passed in from parent, it is
  /// assumed to be drawn on card color, which usually is close enough.
  final Color? onBackgroundColor;

  // Return true if the color is light, meaning it needs dark text for contrast.
  static bool _isLight(final Color color) =>
      ThemeData.estimateBrightnessForColor(color) == Brightness.light;

  // Return true if the color is dark, meaning it needs light text for contrast.
  static bool _isDark(final Color color) =>
      ThemeData.estimateBrightnessForColor(color) == Brightness.dark;

  // On color used when a theme color property does not have a theme onColor.
  static Color _onColor(final Color color, final Color bg) =>
      _isLight(Color.alphaBlend(color, bg)) ? Colors.black : Colors.white;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final ColorScheme colorScheme = theme.colorScheme;
    final bool isDark = colorScheme.brightness == Brightness.dark;
    final bool useMaterial3 = theme.useMaterial3;

    // Grab the card border from the theme card shape
    ShapeBorder? border = theme.cardTheme.shape;
    // If we had one, copy in a border side to it.
    if (border is RoundedRectangleBorder) {
      border = border.copyWith(
        side: BorderSide(
          color: theme.dividerColor,
          width: 1,
        ),
      );
      // If
    } else {
      // If border was null, make one matching Card default, but with border
      // side, if it was not null, we leave it as it was.
      border ??= RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(useMaterial3 ? 12 : 4)),
        side: BorderSide(
          color: theme.dividerColor,
          width: 1,
        ),
      );
    }

    // Get effective background color.
    final Color background =
        onBackgroundColor ?? theme.cardTheme.color ?? theme.cardColor;

    // Warning label for scaffold background when it uses to much blend.
    final String surfaceTooHigh = isDark
        ? _isLight(theme.colorScheme.surface)
            ? '\nTOO HIGH'
            : ''
        : _isDark(theme.colorScheme.surface)
            ? '\nTOO HIGH'
            : '';

    // Warning label for scaffold background when it uses to much blend.
    final String backTooHigh = isDark
        ? _isLight(theme.colorScheme.background)
            ? '\nTOO HIGH'
            : ''
        : _isDark(theme.colorScheme.background)
            ? '\nTOO HIGH'
            : '';

    // Wrap this widget branch in a custom theme where card has a border outline
    // if it did not have one, but retains in ambient themed border radius.
    return Theme(
      data: Theme.of(context).copyWith(
        cardTheme: CardTheme.of(context).copyWith(
          elevation: 0,
          shape: border,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Text(
              'ColorScheme Colors',
              style: theme.textTheme.titleMedium,
            ),
          ),
          Wrap(
            alignment: WrapAlignment.start,
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 6,
            runSpacing: 6,
            children: <Widget>[
              ColorCard(
                label: 'Primary',
                color: colorScheme.primary,
                textColor: colorScheme.onPrimary,
              ),
              ColorCard(
                label: 'on\nPrimary',
                color: colorScheme.onPrimary,
                textColor: colorScheme.primary,
              ),
              ColorCard(
                label: 'Primary\nContainer',
                color: colorScheme.primaryContainer,
                textColor: colorScheme.onPrimaryContainer,
              ),
              ColorCard(
                label: 'onPrimary\nContainer',
                color: colorScheme.onPrimaryContainer,
                textColor: colorScheme.primaryContainer,
              ),
              ColorCard(
                label: 'Secondary',
                color: colorScheme.secondary,
                textColor: colorScheme.onSecondary,
              ),
              ColorCard(
                label: 'on\nSecondary',
                color: colorScheme.onSecondary,
                textColor: colorScheme.secondary,
              ),
              ColorCard(
                label: 'Secondary\nContainer',
                color: colorScheme.secondaryContainer,
                textColor: colorScheme.onSecondaryContainer,
              ),
              ColorCard(
                label: 'on\nSecondary\nContainer',
                color: colorScheme.onSecondaryContainer,
                textColor: colorScheme.secondaryContainer,
              ),
              ColorCard(
                label: 'Tertiary',
                color: colorScheme.tertiary,
                textColor: colorScheme.onTertiary,
              ),
              ColorCard(
                label: 'on\nTertiary',
                color: colorScheme.onTertiary,
                textColor: colorScheme.tertiary,
              ),
              ColorCard(
                label: 'Tertiary\nContainer',
                color: colorScheme.tertiaryContainer,
                textColor: colorScheme.onTertiaryContainer,
              ),
              ColorCard(
                label: 'on\nTertiary\nContainer',
                color: colorScheme.onTertiaryContainer,
                textColor: colorScheme.tertiaryContainer,
              ),
              ColorCard(
                label: 'Error',
                color: colorScheme.error,
                textColor: colorScheme.onError,
              ),
              ColorCard(
                label: 'on\nError',
                color: colorScheme.onError,
                textColor: colorScheme.error,
              ),
              ColorCard(
                label: 'Error\nContainer',
                color: colorScheme.errorContainer,
                textColor: colorScheme.onErrorContainer,
              ),
              ColorCard(
                label: 'onError\nContainer',
                color: colorScheme.onErrorContainer,
                textColor: colorScheme.errorContainer,
              ),
              ColorCard(
                label: 'Background$backTooHigh',
                color: colorScheme.background,
                textColor: colorScheme.onBackground,
              ),
              ColorCard(
                label: 'on\nBackground',
                color: colorScheme.onBackground,
                textColor: colorScheme.background,
              ),
              ColorCard(
                label: 'Surface$surfaceTooHigh',
                color: colorScheme.surface,
                textColor: colorScheme.onSurface,
              ),
              ColorCard(
                label: 'on\nSurface',
                color: colorScheme.onSurface,
                textColor: colorScheme.surface,
              ),
              ColorCard(
                label: 'Surface\nVariant',
                color: colorScheme.surfaceVariant,
                textColor: colorScheme.onSurfaceVariant,
              ),
              ColorCard(
                label: 'onSurface\nVariant',
                color: colorScheme.onSurfaceVariant,
                textColor: colorScheme.surfaceVariant,
              ),
              ColorCard(
                label: 'Outline',
                color: colorScheme.outline,
                textColor: colorScheme.background,
              ),
              ColorCard(
                label: 'Shadow',
                color: colorScheme.shadow,
                textColor: _onColor(colorScheme.shadow, background),
              ),
              ColorCard(
                label: 'Inverse\nSurface',
                color: colorScheme.inverseSurface,
                textColor: colorScheme.onInverseSurface,
              ),
              ColorCard(
                label: 'onInverse\nSurface',
                color: colorScheme.onInverseSurface,
                textColor: colorScheme.inverseSurface,
              ),
              ColorCard(
                label: 'Inverse\nPrimary',
                color: colorScheme.inversePrimary,
                textColor: colorScheme.primary,
              ),
              ColorCard(
                label: 'Surface\nTint',
                color: colorScheme.surfaceTint,
                textColor: colorScheme.onPrimary,
              ),
            ],
          ),
        ],
      ),
    );
  }
}

/// Draw a number of boxes showing the colors of key theme color properties
/// in the ColorScheme of the inherited ThemeData and some of its key color
/// properties.
class ShowThemeDataColors extends StatelessWidget {
  const ShowThemeDataColors({
    super.key,
    this.onBackgroundColor,
  });

  /// The color of the background the color widget are being drawn on.
  ///
  /// Some of the theme colors may have semi-transparent fill color. To compute
  /// a legible text color for the sum when it shown on a background color, we
  /// need to alpha merge it with background and we need the exact background
  /// color it is drawn on for that. If not passed in from parent, it is
  /// assumed to be drawn on card color, which usually is close enough.
  final Color? onBackgroundColor;

  // Return true if the color is light, meaning it needs dark text for contrast.
  static bool _isLight(final Color color) =>
      ThemeData.estimateBrightnessForColor(color) == Brightness.light;

  // Return true if the color is dark, meaning it needs light text for contrast.
  static bool _isDark(final Color color) =>
      ThemeData.estimateBrightnessForColor(color) == Brightness.dark;

  // On color used when a theme color property does not have a theme onColor.
  static Color _onColor(final Color color, final Color background) =>
      _isLight(Color.alphaBlend(color, background))
          ? Colors.black
          : Colors.white;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final ColorScheme colorScheme = theme.colorScheme;
    final bool isDark = colorScheme.brightness == Brightness.dark;
    final bool useMaterial3 = theme.useMaterial3;

    // Grab the card border from the theme card shape
    ShapeBorder? border = theme.cardTheme.shape;
    // If we had one, copy in a border side to it.
    if (border is RoundedRectangleBorder) {
      border = border.copyWith(
        side: BorderSide(
          color: theme.dividerColor,
          width: 1,
        ),
      );
    } else {
      // If border was null, make one matching Card default, but with border
      // side, if it was not null, we leave it as it was.
      border ??= RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(useMaterial3 ? 12 : 4)),
        side: BorderSide(
          color: theme.dividerColor,
          width: 1,
        ),
      );
    }

    // Get effective background color.
    final Color background =
        onBackgroundColor ?? theme.cardTheme.color ?? theme.cardColor;

    // Warning label for scaffold background when it uses to much blend.
    final String scaffoldTooHigh = isDark
        ? _isLight(theme.scaffoldBackgroundColor)
            ? '\nTOO HIGH'
            : ''
        : _isDark(theme.scaffoldBackgroundColor)
            ? '\nTOO HIGH'
            : '';
    // Warning label for scaffold background when it uses to much blend.
    final String surfaceTooHigh = isDark
        ? _isLight(theme.colorScheme.surface)
            ? '\nTOO HIGH'
            : ''
        : _isDark(theme.colorScheme.surface)
            ? '\nTOO HIGH'
            : '';

    // Warning label for scaffold background when it uses to much blend.
    final String backTooHigh = isDark
        ? _isLight(theme.colorScheme.background)
            ? '\nTOO HIGH'
            : ''
        : _isDark(theme.colorScheme.background)
            ? '\nTOO HIGH'
            : '';

    // Wrap this widget branch in a custom theme where card has a border outline
    // if it did not have one, but retains in ambient themed border radius.
    return Theme(
      data: Theme.of(context).copyWith(
        cardTheme: CardTheme.of(context).copyWith(
          elevation: 0,
          shape: border,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Text(
              'ThemeData Colors',
              style: theme.textTheme.titleMedium,
            ),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 6,
            runSpacing: 6,
            crossAxisAlignment: WrapCrossAlignment.center,
            children: <Widget>[
              ColorCard(
                label: 'Primary\nColor',
                color: theme.primaryColor,
                textColor: _onColor(theme.primaryColor, background),
              ),
              ColorCard(
                label: 'Primary\nDark',
                color: theme.primaryColorDark,
                textColor: _onColor(theme.primaryColorDark, background),
              ),
              ColorCard(
                label: 'Primary\nLight',
                color: theme.primaryColorLight,
                textColor: _onColor(theme.primaryColorLight, background),
              ),
              ColorCard(
                label: 'Secondary\nHeader',
                color: theme.secondaryHeaderColor,
                textColor: _onColor(theme.secondaryHeaderColor, background),
              ),
              ColorCard(
                label: 'Toggleable\nActive',
                color: theme.toggleableActiveColor,
                textColor: _onColor(theme.toggleableActiveColor, background),
              ),
              ColorCard(
                label: 'Bottom\nAppBar',
                color: theme.bottomAppBarColor,
                textColor: _onColor(theme.bottomAppBarColor, background),
              ),
              ColorCard(
                label: 'Error\nColor',
                color: theme.errorColor,
                textColor: colorScheme.onError,
              ),
              ColorCard(
                label: 'Canvas$backTooHigh',
                color: theme.canvasColor,
                textColor: _onColor(theme.canvasColor, background),
              ),
              ColorCard(
                label: 'Card$surfaceTooHigh',
                color: theme.cardColor,
                textColor: _onColor(theme.cardColor, background),
              ),
              ColorCard(
                label: 'Scaffold\nBackground$scaffoldTooHigh',
                color: theme.scaffoldBackgroundColor,
                textColor: _onColor(theme.scaffoldBackgroundColor, background),
              ),
              ColorCard(
                label: 'Dialog',
                color: theme.dialogBackgroundColor,
                textColor: _onColor(theme.dialogBackgroundColor, background),
              ),
              ColorCard(
                label: 'Indicator\nColor',
                color: theme.indicatorColor,
                textColor: _onColor(theme.indicatorColor, background),
              ),
              ColorCard(
                label: 'Divider\nColor',
                color: theme.dividerColor,
                textColor: _onColor(theme.dividerColor, background),
              ),
              ColorCard(
                label: 'Disabled\nColor',
                color: theme.disabledColor,
                textColor: _onColor(theme.disabledColor, background),
              ),
              ColorCard(
                label: 'Hover\nColor',
                color: theme.hoverColor,
                textColor: _onColor(theme.hoverColor, background),
              ),
              ColorCard(
                label: 'Focus\nColor',
                color: theme.focusColor,
                textColor: _onColor(theme.focusColor, background),
              ),
              ColorCard(
                label: 'Highlight\nColor',
                color: theme.highlightColor,
                textColor: _onColor(theme.highlightColor, background),
              ),
              ColorCard(
                label: 'Splash\nColor',
                color: theme.splashColor,
                textColor: _onColor(theme.splashColor, background),
              ),
              ColorCard(
                label: 'Shadow\nColor',
                color: theme.shadowColor,
                textColor: _onColor(theme.shadowColor, background),
              ),
              ColorCard(
                label: 'Hint\nColor',
                color: theme.hintColor,
                textColor: _onColor(theme.hintColor, background),
              ),
              ColorCard(
                label: 'Selected\nRow',
                color: theme.selectedRowColor,
                textColor: _onColor(theme.selectedRowColor, background),
              ),
              ColorCard(
                label: 'Unselected\nWidget',
                color: theme.unselectedWidgetColor,
                textColor: _onColor(theme.unselectedWidgetColor, background),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class ColorCard extends StatelessWidget {
  const ColorCard({
    super.key,
    required this.label,
    required this.color,
    required this.textColor,
    this.size,
  });

  final String label;
  final Color color;
  final Color textColor;
  final Size? size;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 86,
      height: 58,
      child: Card(
        margin: EdgeInsets.zero,
        clipBehavior: Clip.antiAlias,
        color: color,
        child: Center(
          child: Text(
            label,
            style: TextStyle(color: textColor, fontSize: 11),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}

M3 demo of no elevation on PopupMenuButton, BottomNavigationBar, NavigationRail, AlertDialog

M2 Mode M3 mode
Screenshot 2022-07-06 at 22 12 11 Screenshot 2022-07-06 at 22 12 42

M3 demo of no elevation on TimePickerDialog, DatePickerDialog

M2 Mode M3 mode
Screenshot 2022-07-06 at 22 13 04 Screenshot 2022-07-06 at 22 13 18

M3 demo of no elevation on MaterialBanner, BottomSheet

This also shows how the underlying Material behaves, that causes the elevation issue for all the other widgets. As can be seen, only elevation specified begets no elevation of Material when useMaterial3 is set to true. In a way this also breaks past and expected behaviour of the Material widget.

M2 Mode M3 mode
Screenshot 2022-07-06 at 22 13 40 Screenshot 2022-07-06 at 22 13 54
Flutter doctor
flutter doctor -v
[✓] Flutter (Channel master, 3.1.0-0.0.pre.1515, on macOS 12.4 21F79 darwin-arm, locale en-FI)
    • Flutter version 3.1.0-0.0.pre.1515 on channel master at /Users/rydmike/fvm/versions/master
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 16bbef188f (54 minutes ago), 2022-07-06 11:14:07 -0700
    • Engine revision ea9e0d0ac5
    • Dart version 2.18.0 (build 2.18.0-258.0.dev)
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/rydmike/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F17a
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2022.1.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 67.1.4
    • Dart plugin version 221.5591.58

[✓] VS Code (version 1.68.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.44.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 12.4 21F79 darwin-arm
    • Chrome (web)    • chrome • web-javascript • Google Chrome 103.0.5060.114

[✓] HTTP Host Availability
    • All required HTTP hosts are available

@danagbemava-nc danagbemava-nc added in triage Presently being triaged by the triage team framework flutter/packages/flutter repository. See also f: labels. f: material design flutter/packages/flutter/material repository. c: proposal A detailed proposal for a change to Flutter and removed in triage Presently being triaged by the triage team labels Jul 7, 2022
@TahaTesser TahaTesser added the customer: crowd Affects or could affect many people, though not necessarily a specific customer. label Jul 8, 2022
rydmike added a commit to rydmike/flex_color_scheme that referenced this issue Jul 8, 2022
To avoid having this issue visible as default in Theme Playground
we default useMaterial3 until it is fixed or behaves better
flutter/flutter#107190
rydmike added a commit to rydmike/flex_color_scheme that referenced this issue Jul 8, 2022
* Deprecated m3TextTheme and use SDK built in Typography instead

* Deprcate: FlexSubThemes.buttonTheme

* Bump package versions

* Update to use super.params, new in Dart 2.17

* Update LinkTextSpan to use Uri instead of deprecated url

* Dep updates

* Add larg FAB to theme showcase

* Make Example custom themed Cards, also respect useMaterial3

* Add surfaceTint color to SchemeColor enum and functions

* Add basic support for surfaceTint

* Three more panel M3 useMaterial3 behavior added

* Fix lint

* Typo/comment corrections

* Add support for Flutter 3.0 Theme Extensions

* iOs and macOS

* Bump package versions

* DroidSans font not available anymore in Google Fons 3.0.0 package, replace with Fira Mono

* Update change log and TODOs

* Bump example version info

* Opt-in sub theme toggleables now default to primary instead of secondary

* Playground: Toggleable colors and efault text update. Add M3 switch to UI.

* Playground: FAB fix of default text when using M3

* Remove not needed TODOs

* Correct FAB color behavior when useMaterail3 is true

* Doc and typo fixes

* Playground app: Workaround for issue flutter/flutter#103864

* FAB component theme color indicator fix for useM3

* PopupMenu style change

* M3 defaults support for NavigationBar

* Fix Material theme showcase when using M3

* Themes Playground - update M3 presentation of Card

* Update CHANGELOG.md

* Doc updates

* Doc updates

* Doc updates

* FIX NavigationRail M3 defaults

* FIX test for new default rail size 14-12dp

* Playground intro text update. Flutter version info update.

* Doc updates

* Doc updates

* Doc updates

* Add full support for surfaceTint color, so it is also used as FCS blend color. Needs tests!

* Custom surfaceTint and surface blends support in Playground

* Example fixes

* Update CHANGELOG.md

* Cleaning: Hashcode algo changed. Remove not needed finals.

* Lint: Remove not needed finals.
* HasCode: Change to Object.hash (used jenkins deprecated in master).

* Set defaultUseMaterial3 = false due to Flutter issue  107190

To avoid having this issue visible as default in Theme Playground
we default useMaterial3 until it is fixed or behaves better
flutter/flutter#107190

* Initial/early support for M3 TextField style.

* Update flex_theme_mode_switch.dart

* Fix InputDecorator test. Update changelog date
@darrenaustin
Copy link
Contributor

Thanks for the well thought out and documented issue @rydmike!

Potential and Proposed Fix

Please consider changing Material default behaviour when useMaterial3 is true so that it uses theme colorScheme.shadow for shadowColor, and colorScheme.surfaceTint for surfaceTintColor as defaults.

This would make M3 mode Material get M3 style elevation (shadow and tint) by default when specifying only elevation, as before when using Material. Flutter SDK widgets that have not yet been migrated to support M3 internally, would then get M3 style tinted elevation with shadow, when only elevation is used. Such Flutter SDK widgets can then later implement their own more correct M3 elevation design, be it no elevation, shadow or tint only based elevation.

The core issue with this proposal (if I am understanding it correctly) is that in M3 there are widgets that are supposed to show elevation with just a surface tint, just a drop shadow, or both. In order to support all of these options while keeping minimal changes to the API, we chose to determine which of these are presented based on whether the corresponding color was non-null. That is, if a widget needs just a surface tint, just supply the surface tint color and no shadow color. If it needs both, supply both, etc.

If we always default the Material widget's shadow color to ColorScheme.shadow and the surface tint color to ColorScheme.surfaceTint then everything with an elevation would display both a drop shadow and a surface tint, with no way to turn either of them off.

An alternative that was considered was to have another parameter added to Material that would control how the elevation was presented, something like:

enum MaterialElevationPresentation { shadow, surfaceTint, shadowAndTint }

Or just values for shadow and surfaceTint and then have a Set of them as the property in the Material widget (which seems like overkill).

Unfortunately, this would mean that for every widget built on top of Material that exposed its elevation (like Dialogs), we would need to not only add the shadowColor, and surfaceTintColor, but this new presentation value as well.

That said, we completely understand the issues that this is causing during the migration. We'll think some more about this and see if we can find a way to make this better in the interim.

@rydmike
Copy link
Contributor Author

rydmike commented Jul 27, 2022

Hi @darrenaustin, yes I looked at the Material code when digging into why all the mentioned widgets behave the way they do. Which is why I also agree that it is a tricky situation with no good, or at least no optimal solution. That's why I also mentioned that I don't really have any good suggestion that would work well either.

If all SDK widgets (dialogs, banners, popup etc and their themes, if they have one) that use Material would already now expose shadowColor and surfaceTintColor in addition to elevation, even if they do not implement Material 3 yet, that would actually offer a workaround since then you could at least fix the situation, now you can't.

Since Material using widgets in M3 will need to expose those Material properties anyway, so you can modify and theme them, it would be a step towards M3 to do that before they actually fully implement M3. It then becomes less time critical to get all M3 specs implemented for widgets using Material that now suffer during the transition when you opt-in on M3.

We still have the situation of being forced to also migrate any custom widgets built on Material when you migrate to M3, if you want to see any type of elevation at all on them, be it shadow or tint. At least for your own you have access to them and can fix it easily. Still I can imagine many packages lagging behind on this going forward too.

My other thoughts on a fix for this was that maybe Material needs its own useMaterial3 flag as a property, that defaults to false so that it is not by default using the context based ThemeData useMaterial3 flag automatically.

Widgets that now or later implement M3, then use context theme useMaterial3 and pass in its useMaterial3 to Material's useMaterial3 property. We then get "M2" elevation based style on anything that has not yet been migrated to M3 in the framework, even when we opt-in on M3, but M3 style on those that have been migrated. As a bonus, custom widgets and packages using Material would not get their elevation broken when the apps using them opt-in on M3. The custom widgets and packages can pass along the useMaterial3 to their Material, expose shadowColor and surfaceTintColor when they add support for it. Just a thought, has its challenges too, but it could work.

@github-actions
Copy link

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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 26, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
c: proposal A detailed proposal for a change to Flutter customer: crowd Affects or could affect many people, though not necessarily a specific customer. f: material design flutter/packages/flutter/material repository. framework flutter/packages/flutter repository. See also f: labels. r: fixed Issue is closed as already fixed in a newer version
Projects
No open projects
Status: Done
Development

Successfully merging a pull request may close this issue.

5 participants
@darrenaustin @rydmike @TahaTesser @danagbemava-nc and others