Fix showSnackBar can't access useMaterial3 from the theme (#157707)

## Description

This PR makes it possible for the `MaterialApp` built in `ScaffoldMessenger` state to access the ambient theme.

Before this PR, the built in messenger was above the theme.
After this PR, the build in messenger is below the theme.

## Related Issue

Fixes [Can't access useMaterial3 from the theme in the showSnackBar method](https://github.com/flutter/flutter/issues/115924)

## Tests

Adds 1 test.
This commit is contained in:
Bruno Leroux 2024-10-31 22:04:57 +01:00 committed by GitHub
parent 0fe615343b
commit 5f65bd06c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 35 additions and 9 deletions

View File

@ -986,6 +986,16 @@ class _MaterialAppState extends State<MaterialApp> {
},
);
}
childWidget = ScaffoldMessenger(
key: widget.scaffoldMessengerKey,
child: DefaultSelectionStyle(
selectionColor: effectiveSelectionColor,
cursorColor: effectiveCursorColor,
child: childWidget,
),
);
if (widget.themeAnimationStyle != AnimationStyle.noAnimation) {
childWidget = AnimatedTheme(
data: theme,
@ -1000,14 +1010,7 @@ class _MaterialAppState extends State<MaterialApp> {
);
}
return ScaffoldMessenger(
key: widget.scaffoldMessengerKey,
child: DefaultSelectionStyle(
selectionColor: effectiveSelectionColor,
cursorColor: effectiveCursorColor,
child: childWidget,
),
);
return childWidget;
}
Widget _buildWidgetApp(BuildContext context) {

View File

@ -2867,7 +2867,30 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('ScaffoldMessenger showSnackBar default animation', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/115924.
testWidgets('Default ScaffoldMessenger can access ambient theme', (WidgetTester tester) async {
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
final ColorScheme colorScheme = ColorScheme.fromSeed(seedColor: Colors.deepPurple);
final ThemeData customTheme = ThemeData(
colorScheme: colorScheme,
visualDensity: VisualDensity.comfortable,
);
await tester.pumpWidget(
MaterialApp(
scaffoldMessengerKey: scaffoldMessengerKey,
theme: customTheme,
home: const SizedBox.shrink(),
),
);
final ThemeData messengerTheme = Theme.of(scaffoldMessengerKey.currentContext!);
expect(messengerTheme.colorScheme, colorScheme);
expect(messengerTheme.visualDensity, VisualDensity.comfortable);
});
testWidgets('ScaffoldMessenger showSnackBar default animation', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(