Fix unattached MenuController throws assertion error when calling MenuController.close() (#156588)
Fixes [Closing a menu controller that was never attached throws an assertion error](https://github.com/flutter/flutter/issues/156572) ### Code sample <details> <summary>expand to view the code sample</summary> ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: () => Navigator.of(context).push( MaterialPageRoute( builder: (context) => const MenuControllerPage(), ), ), child: const Text('Press Me'), ), ), ); } } class MenuControllerPage extends StatefulWidget { const MenuControllerPage({super.key}); @override State<MenuControllerPage> createState() => _MenuControllerPageState(); } class _MenuControllerPageState extends State<MenuControllerPage> { // This menu controller is intentionally left as not attached to a MenuAnchor. final MenuController _menuController = MenuController(); @override void dispose() { // Close the menu when the page is popped. _menuController.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( child: const Text('Go back'), onPressed: () => Navigator.of(context).pop(), ), ), ); } } ``` </details>
This commit is contained in:
@@ -664,8 +664,7 @@ class MenuController {
|
||||
/// scrolled by an ancestor, or the view changes size, then any open menu will
|
||||
/// automatically close.
|
||||
void close() {
|
||||
assert(_anchor != null);
|
||||
_anchor!._close();
|
||||
_anchor?._close();
|
||||
}
|
||||
|
||||
/// Opens the menu that this menu controller is associated with.
|
||||
|
||||
@@ -4718,6 +4718,14 @@ void main() {
|
||||
tester.renderObject(find.byWidget(rootOverlay)),
|
||||
);
|
||||
});
|
||||
|
||||
// Regression test for https://github.com/flutter/flutter/issues/156572.
|
||||
testWidgets('Unattached MenuController does not throw when calling close', (WidgetTester tester) async {
|
||||
final MenuController controller = MenuController();
|
||||
controller.close();
|
||||
await tester.pump();
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
List<Widget> createTestMenus({
|
||||
|
||||
Reference in New Issue
Block a user