From 122ab838f48b728784f088b1560ee52f44ea7054 Mon Sep 17 00:00:00 2001 From: Kate Lovett Date: Wed, 4 May 2022 17:34:11 -0500 Subject: [PATCH] Add assertion that snackbars have a place to go (#103006) --- .../flutter/lib/src/material/scaffold.dart | 5 ++++ .../flutter/test/material/snack_bar_test.dart | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 49f19dcdbf17b..b9164091a5170 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -265,6 +265,11 @@ class ScaffoldMessengerState extends State with TickerProvide /// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart ** /// {@end-tool} ScaffoldFeatureController showSnackBar(SnackBar snackBar) { + assert( + _scaffolds.isNotEmpty, + 'ScaffoldMessenger.showSnackBar was called, but there are currently no ' + 'descendant Scaffolds to present to.', + ); _snackBarController ??= SnackBar.createAnimationController(vsync: this) ..addStatusListener(_handleSnackBarStatusChanged); if (_snackBars.isEmpty) { diff --git a/packages/flutter/test/material/snack_bar_test.dart b/packages/flutter/test/material/snack_bar_test.dart index 2372baae49cde..5132ac5b9662f 100644 --- a/packages/flutter/test/material/snack_bar_test.dart +++ b/packages/flutter/test/material/snack_bar_test.dart @@ -2090,6 +2090,34 @@ void main() { await tester.pump(const Duration(milliseconds: 750)); await expectLater(find.byType(MaterialApp), matchesGoldenFile('snack_bar.goldenTest.backdropFilter.png')); }); + + testWidgets('ScaffoldMessenger will alert for snackbars that cannot be presented', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/103004 + await tester.pumpWidget(const MaterialApp( + home: Center(), + )); + + final ScaffoldMessengerState scaffoldMessengerState = tester.state( + find.byType(ScaffoldMessenger), + ); + expect( + () { + scaffoldMessengerState.showSnackBar(const SnackBar( + content: Text('I am a snack bar.'), + )); + }, + throwsA( + isA().having( + (AssertionError error) => error.toString(), + 'description', + contains( + 'ScaffoldMessenger.showSnackBar was called, but there are currently ' + 'no descendant Scaffolds to present to.' + ) + ), + ), + ); + }); } /// Start test for "SnackBar dismiss test".