Skip to content

Add animation for menus#143416

Closed
QuncCccccc wants to merge 30 commits intoflutter:masterfrom
QuncCccccc:menu_anchor_animation
Closed

Add animation for menus#143416
QuncCccccc wants to merge 30 commits intoflutter:masterfrom
QuncCccccc:menu_anchor_animation

Conversation

@QuncCccccc
Copy link
Contributor

@QuncCccccc QuncCccccc commented Feb 14, 2024

Fixes: #143316 & #143781
This PR is to

  • add expand/collapse animation to MenuAnchor and DropdownMenu. On desktop, menus don't show any animations; On mobile, menu size shows animation when it is expanded and collapsed.
  • add sizeAnimationStyle to MenuStyle so we can customize the menu animation.

Default animation:

defaultAnimation.mov

Custom animation:

BounceOutAnimation.mov

Default animation in slow mode:

SlowMode.mov

Pre-launch Checklist

  • I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
  • I read the [Tree Hygiene] wiki page, which explains my responsibilities.
  • I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement].
  • I signed the [CLA].
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making, or this PR is [test-exempt].
  • All existing and new tests are passing.

@github-actions github-actions bot added framework flutter/packages/flutter repository. See also f: labels. f: material design flutter/packages/flutter/material repository. labels Feb 14, 2024
@QuncCccccc QuncCccccc force-pushed the menu_anchor_animation branch from 4424a68 to 1dd43db Compare February 14, 2024 20:34
@QuncCccccc QuncCccccc force-pushed the menu_anchor_animation branch 2 times, most recently from a0f2d47 to 769783b Compare February 28, 2024 08:23
@QuncCccccc QuncCccccc force-pushed the menu_anchor_animation branch 2 times, most recently from 029b5bc to 3f480b9 Compare March 4, 2024 19:01
@github-actions github-actions bot added d: api docs Issues with https://api.flutter.dev/ d: examples Sample code and demos labels Mar 5, 2024
@QuncCccccc QuncCccccc force-pushed the menu_anchor_animation branch from 9000018 to 140caa4 Compare March 7, 2024 20:25
@QuncCccccc QuncCccccc force-pushed the menu_anchor_animation branch 2 times, most recently from d97e09e to a559f69 Compare May 8, 2024 16:38
@QuncCccccc QuncCccccc marked this pull request as ready for review May 8, 2024 16:38
@QuncCccccc
Copy link
Contributor Author

QuncCccccc commented May 21, 2024

Added a g3fix(cl/635622687) for Google testing. The other two failures only show 1 digit of difference.


_menuSize = CurvedAnimation(
parent: _animateController,
curve: effectiveAnimationStyle.curve ?? Curves.linear,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we have a default of linear here? Shouldn't it have been included in all kinds of defaults above?

// Notify that _childIsOpen changed state, but only if not
// currently disposing.
_parent?._childChangedOpenState();
await _animateController.reverse();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it correct to await here instead of at the end of the method? The widget.onClose won't be called before the entire animation has ended.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, do you think it would be a good idea to add a new callback called onCloseAnimationEnd or something? Imagine you're building a menu and you want to remove the MenuAnchor once an option is selected, but immediately removing it upon onClose (suppose we don't wait for the animation, and we shouldn't) might remove the fade out animation entirely (does it?)

Copy link
Contributor

@davidhicks980 davidhicks980 Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • You can ignore this comment now
Long comment about animation handling

When working without access to the MenuAnchor internals, I found it easiest to just treat a closed menu as AnimationStatus.dismissed, and an open menu as anything but AnimationStatus.dismissed, and provide an onAnimationStatusChange callback. Right now, MenuController.isOpen just represents whether the overlay is showing, so it'd probably be least disruptive to keep it that way.

With regard to onAnimationStatusChange, I prefer Tong's method of splitting out callbacks -- at one point, I considered doing onAnimatingClosed, onAnimatingOpen, onClose, onOpen, and will probably change it back. Note that the code below works with simulations, so regular animation code should be simpler.

Ideally, code that changes the internals of MenuAnchor will call _animateClosed when MenuController.close() is called, and _animateOpen when MenuController.open() is called.

  // Sets the menu status to closed and sets the menu animation to 0.0. Does not
  // trigger the root menu to close the overlay.
  void _handleClosed() {
    _animationController.stop();
    _animationController.value = 0;
    _updateMenuStatus(MenuStatus.closed);
  }

  // Sets the menu status to opened and sets the menu animation to 1.0. Does not
  // trigger the root menu to open the overlay.
  void _handleOpened() {
    _animationController.stop();
    _animationController.value = 1;
    _updateMenuStatus(MenuStatus.opened);
  }

  // Animate the menu closed, then trigger the root menu to close the overlay.
  void _animateClosed() {
    if (_menuStatus case MenuStatus.closed || MenuStatus.closing) {
      assert(_debugMenuInfo('Blocked $_animateClosed because the menu is already closing'));
      return;
    }

    // When the animation controller finishes closing, the inner menu's onClose
    // callback will be called, thereby triggering the _handleClosed callback.
    _animationController
      ..stop()
      ..animateWith(
        ClampedSimulation(
          SpringSimulation(
            widget.reverseSpring,
            _animationController.value,
            0.0,
            5.0,
            tolerance: _springTolerance,
          ),
          xMin: 0.0,
          xMax: 1.0,
        ),
      ).whenComplete(_innerMenuController.close); // I had to use two menu controllers to get around the fact that the inner controller would close the overlay when MenuController.close() was called. This is something that I've been trying to think through.

    _updateMenuStatus(MenuStatus.closing);
  }

  void _animateOpen({ui.Offset? position}) {
    if (_menuStatus case MenuStatus.opened || MenuStatus.opening) {
      _innerMenuController.open(position: position);
      _animationController.value = 1.0;
      return;
    }

    if (!_innerMenuController.isOpen) {
      _innerMenuController.open(position: position);
    }

    _animationController
      ..stop()
      ..animateWith(SpringSimulation(
        widget.forwardSpring,
        _animationController.value,
        1.0,
        5.0,
      )).whenComplete(_handleOpened);

    _updateMenuStatus(MenuStatus.opening);

    // When the menu is first opened, set the first focus to the first item in
    // the menu.
    SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
      final BuildContext? panelContext = _panelScrollableKey.currentContext;
      if (mounted && (panelContext?.mounted ?? false)) {
        FocusScope.of(context).setFirstFocus(
          FocusScope.of(panelContext!),
        );
      }
    });
  }

  // Update the menu status and call listeners.
  void _updateMenuStatus(MenuStatus status) {
    if (status == _menuStatus) {
      return;
    }

    final MenuStatus previousStatus = _menuStatus;
    _menuStatus = status;

    // Cannot use a postFrameCallback because focus won't return to the previous
    // focus node when the menu is closed.
    if (mounted && SchedulerBinding.instance.schedulerPhase !=
                   SchedulerPhase.persistentCallbacks) {
      setState(() { /* Mark dirty if mounted and not already building. */ });
    }

    if (previousStatus == MenuStatus.closed) {
      widget.onOpen?.call();
    }

    if (status == MenuStatus.closed) {
      widget.onClose?.call();
    }

    widget.onAnimationStatusChanged?.call(status);
  }

@dkwingsmt
Copy link
Contributor

During manual testing, I've found some issues if you click the open/close button at some specific rate.

  • Sometimes a tap is not recognized.
  • Sometimes the next tap is not recognized.
  • Sometimes the next animation is skipped.

I think there's some state inconsistency due to the asynchronicity.

Screen.Recording.2024-06-24.at.8.25.52.AM.mp4

@flutter-dashboard
Copy link

This pull request executed golden file tests, but it has not been updated in a while (20+ days). Test results from Gold expire after as many days, so this pull request will need to be updated with a fresh commit in order to get results from Gold.

For more guidance, visit Writing a golden file test for package:flutter.

Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing.

@QuncCccccc QuncCccccc marked this pull request as draft July 30, 2024 18:45
@QuncCccccc
Copy link
Contributor Author

Feels it's been a long time not providing an update. I'm currently working on other tasks, but will come back to this PR soon. Change this PR back to draft for now.

@flutter-dashboard
Copy link

This pull request has been changed to a draft. The currently pending flutter-gold status will not be able to resolve until a new commit is pushed or the change is marked ready for review again.

For more guidance, visit Writing a golden file test for package:flutter.

Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing.

@Piinks
Copy link
Contributor

Piinks commented Nov 19, 2024

(PR Triage): @QuncCccccc would you like to continue to leave this open until you return to it?

@QuncCccccc
Copy link
Contributor Author

(PR Triage): @QuncCccccc would you like to continue to leave this open until you return to it?

Ah so sorry for missing this message! Yes, will try to take a look ASAP!

@Jeidoban
Copy link

Hi there @QuncCccccc! Just also reporting I've upgraded some menus in my app to the new DropdownMenu from DropdownButton and now there appears to be no animations when expanding or collapsing the menu. I super appreciate the hard work you've put into this PR, and would love to see it released.

Thank you!

@marcglasberg
Copy link

Hey, I completely disagree that we should have something like a sizeAnimationStyle property. This assumes we always want a size animation. I think we should be able to define whatever animation we want, instead of having a given animation that we cannot change. For example, when I open my menu I want it to fade in, and do a vertical scale animation from, say 0.9 to 1. (see the menu in https://stripe.com for an example of something similar).

@davidhicks980
Copy link
Contributor

davidhicks980 commented Jan 14, 2025

@marcglasberg and also @QuncCccccc: once RawMenuAnchor lands, I have a lower-level api on top of MenuController that enables custom menu animations while preserving the current MenuAnchor/MenuController api. My thought was that the Material menu anchor will be the "out of the box" menu solution that is more refined, but less customizable. The material MenuAnchor animation spec would otherwise be difficult to customize for end users -- it requires applying an opacity transition to each menu item and doesn't complete its size transition. The API is implemented and ready, but RawMenuAnchor needs to land first.

edit: I added an example at https://menu-anchor.web.app/#/animated with corresponding code at https://github.com/davidhicks980/menu_anchor_demo/blob/main/lib/raw_menu_anchor.animated.dart

@Piinks
Copy link
Contributor

Piinks commented Mar 19, 2025

(triage) @QuncCccccc should we close this to revisit after resolving all of the conflicts from the new RawMenuAnchor?

@QuncCccccc
Copy link
Contributor Author

Yes, this PR is implementing animation for menus, so closing this PR.

@QuncCccccc QuncCccccc closed this Mar 19, 2025
@davidhicks980
Copy link
Contributor

Oh actually, we may just want to rename this to "Add animations for material menus", since my PR doesn't add animations to material -- it only adds the API to implement animations.

@QuncCccccc
Copy link
Contributor Author

Oh actually, we may just want to rename this to "Add animations for material menus", since my PR doesn't add animations to material -- it only adds the API to implement animations.

Oh I see. Thanks for letting me know!

github-merge-queue bot pushed a commit that referenced this pull request Jun 24, 2025
Alternative to #163481,
#167537,
#163481 that uses callbacks.

@dkwingsmt - you inspired me to simplify the menu behavior. I didn't end
up using Actions, mainly because nested behavior was unwieldy and
capturing BuildContext has drawbacks. This uses a basic callback
mechanism to animate the menu open and closed. Check out the examples.

<hr />

### The problem
RawMenuAnchor synchronously shows or hides an overlay menu in response
to `MenuController.open()` and `MenuController.close`, respectively.
Because animations cannot be run on a hidden overlay, there currently is
no way for developers to add animations to RawMenuAnchor and its
subclasses (MenuAnchor, DropdownMenuButton, etc).

### The solution
This PR:
- Adds two callbacks -- `onOpenRequested` and `onCloseRequested` -- to
RawMenuAnchor.
- onOpenRequested is called with a position and a showOverlay callback,
which opens the menu when called.
- onCloseRequested is called with a hideOverlay callback, which hides
the menu when called.

When `MenuController.open()` and `MenuController.close()` are called,
onOpenRequested and onCloseRequested are invoked, respectively.

Precursor for #143416,
#135025,
#143712

## Demo


https://github.com/user-attachments/assets/bb14abca-af26-45fe-8d45-289b5d07dab2

```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.

// ignore_for_file: public_member_api_docs

import 'dart:ui' as ui;

import 'package:flutter/material.dart' hide MenuController, RawMenuAnchor, RawMenuOverlayInfo;

import 'raw_menu_anchor.dart';

/// Flutter code sample for a [RawMenuAnchor] that animates a simple menu using
/// [RawMenuAnchor.onOpenRequested] and [RawMenuAnchor.onCloseRequested].
void main() {
  runApp(const App());
}

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

  @OverRide
  State<Menu> createState() => _MenuState();
}

class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  late final AnimationController animationController;
  final MenuController menuController = MenuController();

  @OverRide
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
  }

  @OverRide
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  void _handleMenuOpenRequest(Offset? position, void Function({Offset? position}) showOverlay) {
    // Mount or reposition the menu before animating the menu open.
    showOverlay(position: position);

    if (animationController.isForwardOrCompleted) {
      // If the menu is already open or opening, the animation is already
      // running forward.
      return;
    }

    // Animate the menu into view. This will cancel the closing animation.
    animationController.forward();
  }

  void _handleMenuCloseRequest(VoidCallback hideOverlay) {
    if (!animationController.isForwardOrCompleted) {
      // If the menu is already closed or closing, do nothing.
      return;
    }

    // Animate the menu out of view.
    //
    // Be sure to use `whenComplete` so that the closing animation
    // can be interrupted by an opening animation.
    animationController.reverse().whenComplete(() {
      if (mounted) {
        // Hide the menu after the menu has closed
        hideOverlay();
      }
    });
  }

  @OverRide
  Widget build(BuildContext context) {
    return RawMenuAnchor(
      controller: menuController,
      onOpenRequested: _handleMenuOpenRequest,
      onCloseRequested: _handleMenuCloseRequest,
      overlayBuilder: (BuildContext context, RawMenuOverlayInfo info) {
        final ui.Offset position = info.anchorRect.bottomLeft;
        return Positioned(
          top: position.dy + 5,
          left: position.dx,
          child: TapRegion(
            groupId: info.tapRegionGroupId,
            child: Material(
              color: ColorScheme.of(context).primaryContainer,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              elevation: 3,
              child: SizeTransition(
                sizeFactor: animationController,
                child: const SizedBox(
                  height: 200,
                  width: 150,
                  child: Center(child: Text('Howdy', textAlign: TextAlign.center)),
                ),
              ),
            ),
          ),
        );
      },
      builder: (BuildContext context, MenuController menuController, Widget? child) {
        return FilledButton(
          onPressed: () {
            if (animationController.isForwardOrCompleted) {
              menuController.close();
            } else {
              menuController.open();
            }
          },
          child: const Text('Toggle Menu'),
        );
      },
    );
  }
}

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

  @OverRide
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)),
      home: const Scaffold(body: Center(child: Menu())),
    );
  }
}

```

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md

---------

Co-authored-by: Tong Mu <[email protected]>
mboetger pushed a commit to mboetger/flutter that referenced this pull request Jul 21, 2025
Alternative to flutter#163481,
flutter#167537,
flutter#163481 that uses callbacks.

@dkwingsmt - you inspired me to simplify the menu behavior. I didn't end
up using Actions, mainly because nested behavior was unwieldy and
capturing BuildContext has drawbacks. This uses a basic callback
mechanism to animate the menu open and closed. Check out the examples.

<hr />

### The problem
RawMenuAnchor synchronously shows or hides an overlay menu in response
to `MenuController.open()` and `MenuController.close`, respectively.
Because animations cannot be run on a hidden overlay, there currently is
no way for developers to add animations to RawMenuAnchor and its
subclasses (MenuAnchor, DropdownMenuButton, etc).

### The solution
This PR:
- Adds two callbacks -- `onOpenRequested` and `onCloseRequested` -- to
RawMenuAnchor.
- onOpenRequested is called with a position and a showOverlay callback,
which opens the menu when called.
- onCloseRequested is called with a hideOverlay callback, which hides
the menu when called.

When `MenuController.open()` and `MenuController.close()` are called,
onOpenRequested and onCloseRequested are invoked, respectively.

Precursor for flutter#143416,
flutter#135025,
flutter#143712

## Demo


https://github.com/user-attachments/assets/bb14abca-af26-45fe-8d45-289b5d07dab2

```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.

// ignore_for_file: public_member_api_docs

import 'dart:ui' as ui;

import 'package:flutter/material.dart' hide MenuController, RawMenuAnchor, RawMenuOverlayInfo;

import 'raw_menu_anchor.dart';

/// Flutter code sample for a [RawMenuAnchor] that animates a simple menu using
/// [RawMenuAnchor.onOpenRequested] and [RawMenuAnchor.onCloseRequested].
void main() {
  runApp(const App());
}

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

  @OverRide
  State<Menu> createState() => _MenuState();
}

class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  late final AnimationController animationController;
  final MenuController menuController = MenuController();

  @OverRide
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
  }

  @OverRide
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  void _handleMenuOpenRequest(Offset? position, void Function({Offset? position}) showOverlay) {
    // Mount or reposition the menu before animating the menu open.
    showOverlay(position: position);

    if (animationController.isForwardOrCompleted) {
      // If the menu is already open or opening, the animation is already
      // running forward.
      return;
    }

    // Animate the menu into view. This will cancel the closing animation.
    animationController.forward();
  }

  void _handleMenuCloseRequest(VoidCallback hideOverlay) {
    if (!animationController.isForwardOrCompleted) {
      // If the menu is already closed or closing, do nothing.
      return;
    }

    // Animate the menu out of view.
    //
    // Be sure to use `whenComplete` so that the closing animation
    // can be interrupted by an opening animation.
    animationController.reverse().whenComplete(() {
      if (mounted) {
        // Hide the menu after the menu has closed
        hideOverlay();
      }
    });
  }

  @OverRide
  Widget build(BuildContext context) {
    return RawMenuAnchor(
      controller: menuController,
      onOpenRequested: _handleMenuOpenRequest,
      onCloseRequested: _handleMenuCloseRequest,
      overlayBuilder: (BuildContext context, RawMenuOverlayInfo info) {
        final ui.Offset position = info.anchorRect.bottomLeft;
        return Positioned(
          top: position.dy + 5,
          left: position.dx,
          child: TapRegion(
            groupId: info.tapRegionGroupId,
            child: Material(
              color: ColorScheme.of(context).primaryContainer,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              elevation: 3,
              child: SizeTransition(
                sizeFactor: animationController,
                child: const SizedBox(
                  height: 200,
                  width: 150,
                  child: Center(child: Text('Howdy', textAlign: TextAlign.center)),
                ),
              ),
            ),
          ),
        );
      },
      builder: (BuildContext context, MenuController menuController, Widget? child) {
        return FilledButton(
          onPressed: () {
            if (animationController.isForwardOrCompleted) {
              menuController.close();
            } else {
              menuController.open();
            }
          },
          child: const Text('Toggle Menu'),
        );
      },
    );
  }
}

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

  @OverRide
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)),
      home: const Scaffold(body: Center(child: Menu())),
    );
  }
}

```

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md

---------

Co-authored-by: Tong Mu <[email protected]>
@davidhicks980
Copy link
Contributor

Howdy @QuncCccccc and @Piinks. Were you all planning on reopening this PR, or committing a new PR? Also, let me know if I can provide any assistance!

@QuncCccccc
Copy link
Contributor Author

Hey @davidhicks980! Probably no, I currently don't have enough time to work on this feature. Please feel free to open a new PR if you want to work on it:)Thanks!

github-merge-queue bot pushed a commit that referenced this pull request Jan 29, 2026
* Adds MD3 animations to MenuAnchor. 
* Adds a "hoverOpenDelay" parameter on `SubmenuButton`
* Moves the layout algorithm from SingleChildLayoutDelegate to a custom
render object. <s>This was done because I needed to access the dry
layout of the menu panel for the best effect. I'll demonstrate
below.</s> Turns out using dry layout significantly limits what children
you can use with a widget. As a result, I'm calculating the final height
using the inverse height factor.

Fixes #135025

I don't have access to the internal Google documentation, so I did my
best to deduce the spec from
https://github.com/material-components/material-web/blob/main/menu/internal/menu.ts.

This change is currently opt-in via an `animated` parameter on
`MenuAnchor` and `SubmenuButton`. As a result, this is not a breaking
change. Because the PR is already quite large, I chose to not add
animation customization to this PR. I also didn't change any theming
files or `DropdownMenu`.

The only other API addition is a `hoverOpenDelay` parameter on
`SubmenuButton`. This parameter delays the start of a submenu opening by
the specified duration. It is independent of the `animated` parameter.

When `animated == false`, the menu runs its forward and reverse
animations with a duration of 0. I originally disposed of all animation
assets when `animated` was false, but found that the code/testing
complexity to be unwieldy.

<s>Blocked by https://github.com/flutter/flutter/pull/176503</s>

## Examples

* Basic example adapted from material-web


https://github.com/user-attachments/assets/e6d02fab-e11c-4dce-ab82-2fb39c1111e0

* Example showing scrollbar 


https://github.com/user-attachments/assets/847054ba-7218-4e73-9835-019bfa7b5521

* MenuBar usage


https://github.com/user-attachments/assets/8231b1cd-c40c-4f18-af87-1b77b43ecb7b

Thanks to @QuncCccccc and @dkwingsmt for [their work on this
issue.](#143416) Sorry for
throwing a wrench into the original PR by introducing `RawMenuAnchor`...

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

**Note**: The Flutter team is currently trialing the use of [Gemini Code
Assist for
GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code).
Comments from the `gemini-code-assist` bot should not be taken as
authoritative feedback from the Flutter team. If you find its comments
useful you can update your code accordingly, but if you are unsure or
disagree with the feedback, please feel free to wait for a Flutter team
member's review for guidance on which automated comments should be
addressed.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
flutter-zl pushed a commit to flutter-zl/flutter that referenced this pull request Feb 10, 2026
…6494)

* Adds MD3 animations to MenuAnchor. 
* Adds a "hoverOpenDelay" parameter on `SubmenuButton`
* Moves the layout algorithm from SingleChildLayoutDelegate to a custom
render object. <s>This was done because I needed to access the dry
layout of the menu panel for the best effect. I'll demonstrate
below.</s> Turns out using dry layout significantly limits what children
you can use with a widget. As a result, I'm calculating the final height
using the inverse height factor.

Fixes flutter#135025

I don't have access to the internal Google documentation, so I did my
best to deduce the spec from
https://github.com/material-components/material-web/blob/main/menu/internal/menu.ts.

This change is currently opt-in via an `animated` parameter on
`MenuAnchor` and `SubmenuButton`. As a result, this is not a breaking
change. Because the PR is already quite large, I chose to not add
animation customization to this PR. I also didn't change any theming
files or `DropdownMenu`.

The only other API addition is a `hoverOpenDelay` parameter on
`SubmenuButton`. This parameter delays the start of a submenu opening by
the specified duration. It is independent of the `animated` parameter.

When `animated == false`, the menu runs its forward and reverse
animations with a duration of 0. I originally disposed of all animation
assets when `animated` was false, but found that the code/testing
complexity to be unwieldy.

<s>Blocked by https://github.com/flutter/flutter/pull/176503</s>

## Examples

* Basic example adapted from material-web


https://github.com/user-attachments/assets/e6d02fab-e11c-4dce-ab82-2fb39c1111e0

* Example showing scrollbar 


https://github.com/user-attachments/assets/847054ba-7218-4e73-9835-019bfa7b5521

* MenuBar usage


https://github.com/user-attachments/assets/8231b1cd-c40c-4f18-af87-1b77b43ecb7b

Thanks to @QuncCccccc and @dkwingsmt for [their work on this
issue.](flutter#143416) Sorry for
throwing a wrench into the original PR by introducing `RawMenuAnchor`...

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

**Note**: The Flutter team is currently trialing the use of [Gemini Code
Assist for
GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code).
Comments from the `gemini-code-assist` bot should not be taken as
authoritative feedback from the Flutter team. If you find its comments
useful you can update your code accordingly, but if you are unsure or
disagree with the feedback, please feel free to wait for a Flutter team
member's review for guidance on which automated comments should be
addressed.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

d: api docs Issues with https://api.flutter.dev/ d: examples Sample code and demos f: material design flutter/packages/flutter/material repository. framework flutter/packages/flutter repository. See also f: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dropdown menus should support animated open/close transitions

6 participants