diff --git a/packages/flutter/lib/src/material/app.dart b/packages/flutter/lib/src/material/app.dart index 0b68542374..4a80123f79 100644 --- a/packages/flutter/lib/src/material/app.dart +++ b/packages/flutter/lib/src/material/app.dart @@ -968,25 +968,25 @@ class _MaterialAppState extends State { Widget childWidget = child ?? const SizedBox.shrink(); + if (widget.builder != null) { + childWidget = Builder( + builder: (BuildContext context) { + // Why are we surrounding a builder with a builder? + // + // The widget.builder may contain code that invokes + // Theme.of(), which should return the theme we selected + // above in AnimatedTheme. However, if we invoke + // widget.builder() directly as the child of AnimatedTheme + // then there is no BuildContext separating them, the + // widget.builder() will not find the theme. Therefore, we + // surround widget.builder with yet another builder so that + // a context separates them and Theme.of() correctly + // resolves to the theme we passed to AnimatedTheme. + return widget.builder!(context, child); + }, + ); + } if (widget.themeAnimationStyle != AnimationStyle.noAnimation) { - if (widget.builder != null) { - childWidget = Builder( - builder: (BuildContext context) { - // Why are we surrounding a builder with a builder? - // - // The widget.builder may contain code that invokes - // Theme.of(), which should return the theme we selected - // above in AnimatedTheme. However, if we invoke - // widget.builder() directly as the child of AnimatedTheme - // then there is no Context separating them, and the - // widget.builder() will not find the theme. Therefore, we - // surround widget.builder with yet another builder so that - // a context separates them and Theme.of() correctly - // resolves to the theme we passed to AnimatedTheme. - return widget.builder!(context, child); - }, - ); - } childWidget = AnimatedTheme( data: theme, duration: widget.themeAnimationStyle?.duration ?? widget.themeAnimationDuration, diff --git a/packages/flutter/test/material/app_test.dart b/packages/flutter/test/material/app_test.dart index 2a01908e05..3431fc0e15 100644 --- a/packages/flutter/test/material/app_test.dart +++ b/packages/flutter/test/material/app_test.dart @@ -1662,6 +1662,22 @@ void main() { expect(tester.getSize(find.byType(MaterialApp)), const Size(123, 456)); }); + + // Regression test for https://github.com/flutter/flutter/issues/156959. + testWidgets( + 'MaterialApp with builder works when themeAnimationStyle is AnimationStyle.noAnimation', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + themeAnimationStyle: AnimationStyle.noAnimation, + builder: (BuildContext context, Widget? child) { + return const Text('Works'); + }, + ), + ); + expect(find.text('Works'), findsOne); + }, + ); } class MockScrollBehavior extends ScrollBehavior {