Skip to content

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.

Copy link
Contributor

@dkwingsmt dkwingsmt left a comment

Choose a reason for hiding this comment

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

In general looks good. But I'm concerned about the design of the parameters for customizing animation. I recommend splitting it into a new PR for more thorough discussion.

} else if (anchorWidth != null){
effectiveMenuStyle = effectiveMenuStyle.copyWith(minimumSize: MaterialStatePropertyAll<Size?>(Size(anchorWidth, 0.0)));
final VisualDensity visualDensity = effectiveMenuStyle.visualDensity ?? Theme.of(context).visualDensity;
final double dx = (visualDensity.horizontal) * 4;
Copy link
Contributor

Choose a reason for hiding this comment

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

What's this used for? Why is it 4 times?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah I should add some explanation above this calculation.

After we get the size of the text field, the width of the menu buttons should be the same as the width of the text field, but the _menuPanel in menu_anchor.dart will change the width a little bit further based on the visual density(here), so the result will be the menu is always a little narrower/wider than the text field. This calculation here is to restore the visual density adjustment to make sure the widths are equal. And this "4" comes from the adjustment.

Copy link
Contributor

Choose a reason for hiding this comment

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

Will it work this way?

final double dx = -visualDensity.baseSizeAdjustment.dx;

reverseCurve: effectiveAnimationStyle.reverseCurve,
);

if (effectiveAnimationStyle == defaultAnimationStyle) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this special treatment needed? Does it make custom animation styles less capable?

Copy link
Contributor Author

@QuncCccccc QuncCccccc Jun 17, 2024

Choose a reason for hiding this comment

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

In the default animation specs(Somehow I can't find the specs page, asking whether the motion designer can send me again:)), we should have size animation and also have fade in/out animation effects. So I added this to only have this opacity animation if a default sizeAnimationStyle is given:)

=> AnimationStyle(
curve: Curves.easeInOutCubicEmphasized,
reverseCurve: Curves.easeInOutCubicEmphasized.flipped,
duration: const Duration(milliseconds: 500),
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is there another 500ms duration? How does this work with the default animation controller in _MenuAnchorState?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the class to define all the defaults from tokens. I've removed the other one! Thanks for catching this!

duration: const Duration(milliseconds: 500),
),
TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows
=> AnimationStyle.noAnimation,
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 clarified in a spec that desktop dropdown menus should have no animation?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No. We don't have specs for desktops. Initially we don't have any animation on menus. Here is just to follow the original behavior:)

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you doc this? Probably just exactly what you said here.

/// the menu size's animation curve. Otherwise, defaults to [Curves.easeInOutCubicEmphasized].
///
/// To disable the animation when menu is open/close, use [AnimationStyle.noAnimation].
final AnimationStyle? sizeAnimationStyle;
Copy link
Contributor

Choose a reason for hiding this comment

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

Does it eliminate the possibility of using different animation for open and close? For example, (although not Material) I observed that the dropdown menus on macOS has no animation for open, but a quick fade out for close.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes! For this PR we only add a sizeAnimationStyle property. I think we can have another opacityAnimationStyle in a following PR if it is needed.

Copy link
Contributor

@dkwingsmt dkwingsmt Jun 24, 2024

Choose a reason for hiding this comment

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

Can we add opacityAnimationStyle in this PR? The special case at L408 (if (effectiveAnimationStyle == defaultAnimationStyle) ) just doesn't feel right.

  • Alternatively, we can hard-code the animation privately in the class and make the entire defaulting and customization in a separate PR. This PR is already hard enough :) (see the issues I've just commented)

Also: I think this property might be better renamed to heightAnimationStyle, since we're hard-coding SizeTransition's axis to be vertical - unless we might also support horizontal in the future (which I doubt.)


_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!

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