Squashed MediaQuery InheritedModel (#114459)

This commit is contained in:
Callum Moffat 2022-12-09 15:59:11 -05:00 committed by GitHub
parent e57b7f4ea8
commit 73cb7c2fc5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
88 changed files with 687 additions and 239 deletions

View File

@ -18,6 +18,17 @@
# * Fixes in this file are from the Cupertino library. * # * Fixes in this file are from the Cupertino library. *
version: 1 version: 1
transforms: transforms:
# Changes made in https://github.com/flutter/flutter/pull/114459
- title: "Migrate to 'boldTextOf'"
date: 2022-10-28
element:
uris: ['widgets.dart', 'material.dart', 'cupertino.dart']
method: 'boldTextOverride'
inClass: 'MediaQuery'
changes:
- kind: 'rename'
newName: 'boldTextOf'
# Change made in https://github.com/flutter/flutter/pull/20649 # Change made in https://github.com/flutter/flutter/pull/20649
# TODO(Piinks): Add tests when `bulkApply:false` testing is supported, https://github.com/dart-lang/sdk/issues/44639 # TODO(Piinks): Add tests when `bulkApply:false` testing is supported, https://github.com/dart-lang/sdk/issues/44639
- title: "Replace with 'CupertinoPopupSurface'" - title: "Replace with 'CupertinoPopupSurface'"

View File

@ -25,6 +25,17 @@
# * ThemeData: fix_theme_data.yaml # * ThemeData: fix_theme_data.yaml
version: 1 version: 1
transforms: transforms:
# Changes made in https://github.com/flutter/flutter/pull/114459
- title: "Migrate to 'boldTextOf'"
date: 2022-10-28
element:
uris: ['widgets.dart', 'material.dart', 'cupertino.dart']
method: 'boldTextOverride'
inClass: 'MediaQuery'
changes:
- kind: 'rename'
newName: 'boldTextOf'
# Changes made in https://github.com/flutter/flutter/pull/15303 # Changes made in https://github.com/flutter/flutter/pull/15303
- title: "Replace 'child' with 'builder'" - title: "Replace 'child' with 'builder'"
date: 2020-12-17 date: 2020-12-17

View File

@ -23,6 +23,17 @@
# * ListWheelScrollView: fix_list_wheel_scroll_view.yaml # * ListWheelScrollView: fix_list_wheel_scroll_view.yaml
version: 1 version: 1
transforms: transforms:
# Changes made in https://github.com/flutter/flutter/pull/114459
- title: "Migrate to 'boldTextOf'"
date: 2022-10-28
element:
uris: ['widgets.dart', 'material.dart', 'cupertino.dart']
method: 'boldTextOverride'
inClass: 'MediaQuery'
changes:
- kind: 'rename'
newName: 'boldTextOf'
# Changes made in https://github.com/flutter/flutter/pull/87839 # Changes made in https://github.com/flutter/flutter/pull/87839
- title: "Migrate to 'disallowIndicator'" - title: "Migrate to 'disallowIndicator'"
date: 2021-08-06 date: 2021-08-06

View File

@ -156,7 +156,7 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final double bottomPadding = MediaQuery.of(context).viewPadding.bottom; final double bottomPadding = MediaQuery.viewPaddingOf(context).bottom;
final Color backgroundColor = CupertinoDynamicColor.resolve( final Color backgroundColor = CupertinoDynamicColor.resolve(
this.backgroundColor ?? CupertinoTheme.of(context).barBackgroundColor, this.backgroundColor ?? CupertinoTheme.of(context).barBackgroundColor,

View File

@ -994,7 +994,7 @@ class CupertinoDynamicColor extends Color with Diagnosticable {
} }
bool isHighContrastEnabled = false; bool isHighContrastEnabled = false;
if (_isHighContrastDependent) { if (_isHighContrastDependent) {
isHighContrastEnabled = MediaQuery.maybeOf(context)?.highContrast ?? false; isHighContrastEnabled = MediaQuery.maybeHighContrastOf(context) ?? false;
} }
final CupertinoUserInterfaceLevelData level = _isInterfaceElevationDependent final CupertinoUserInterfaceLevelData level = _isInterfaceElevationDependent

View File

@ -493,7 +493,7 @@ class _CupertinoContextMenuState extends State<CupertinoContextMenu> with Ticker
// it. // it.
_ContextMenuLocation get _contextMenuLocation { _ContextMenuLocation get _contextMenuLocation {
final Rect childRect = _getRect(_childGlobalKey); final Rect childRect = _getRect(_childGlobalKey);
final double screenWidth = MediaQuery.of(context).size.width; final double screenWidth = MediaQuery.sizeOf(context).width;
final double center = screenWidth / 2; final double center = screenWidth / 2;
final bool centerDividesChild = childRect.left < center final bool centerDividesChild = childRect.left < center
@ -1311,7 +1311,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T
Widget _buildChildAnimation(BuildContext context, Widget? child) { Widget _buildChildAnimation(BuildContext context, Widget? child) {
_lastScale = _getScale( _lastScale = _getScale(
widget.orientation, widget.orientation,
MediaQuery.of(context).size.height, MediaQuery.sizeOf(context).height,
_moveAnimation.value.dy, _moveAnimation.value.dy,
); );
return Transform.scale( return Transform.scale(

View File

@ -158,12 +158,12 @@ class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_Cupertin
} }
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context); final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
final Offset midpointAnchor = Offset( final Offset midpointAnchor = Offset(
clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left, clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left,
mediaQuery.padding.left, mediaQueryPadding.left,
mediaQuery.size.width - mediaQuery.padding.right, MediaQuery.sizeOf(context).width - mediaQueryPadding.right,
), ),
widget.selectionMidpoint.dy - widget.globalEditableRegion.top, widget.selectionMidpoint.dy - widget.globalEditableRegion.top,
); );
@ -171,7 +171,7 @@ class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_Cupertin
final List<Widget> items = <Widget>[]; final List<Widget> items = <Widget>[];
final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
final Widget onePhysicalPixelVerticalDivider = final Widget onePhysicalPixelVerticalDivider =
SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio); SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context));
void addToolbarButton( void addToolbarButton(
String text, String text,

View File

@ -85,9 +85,8 @@ class CupertinoDesktopTextSelectionToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context);
final double paddingAbove = mediaQuery.padding.top + _kToolbarScreenPadding; final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;
final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove); final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);
return Padding( return Padding(

View File

@ -149,8 +149,8 @@ const double _kMaxRegularTextScaleFactor = 1.4;
// Accessibility mode on iOS is determined by the text scale factor that the // Accessibility mode on iOS is determined by the text scale factor that the
// user has selected. // user has selected.
bool _isInAccessibilityMode(BuildContext context) { bool _isInAccessibilityMode(BuildContext context) {
final MediaQueryData? data = MediaQuery.maybeOf(context); final double? factor = MediaQuery.maybeTextScaleFactorOf(context);
return data != null && data.textScaleFactor > _kMaxRegularTextScaleFactor; return factor != null && factor > _kMaxRegularTextScaleFactor;
} }
/// An iOS-style alert dialog. /// An iOS-style alert dialog.
@ -257,7 +257,7 @@ class CupertinoAlertDialog extends StatelessWidget {
final Curve insetAnimationCurve; final Curve insetAnimationCurve;
Widget _buildContent(BuildContext context) { Widget _buildContent(BuildContext context) {
final double textScaleFactor = MediaQuery.of(context).textScaleFactor; final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
final List<Widget> children = <Widget>[ final List<Widget> children = <Widget>[
if (title != null || content != null) if (title != null || content != null)
@ -317,7 +317,7 @@ class CupertinoAlertDialog extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
final bool isInAccessibilityMode = _isInAccessibilityMode(context); final bool isInAccessibilityMode = _isInAccessibilityMode(context);
final double textScaleFactor = MediaQuery.of(context).textScaleFactor; final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
return CupertinoUserInterfaceLevel( return CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated, data: CupertinoUserInterfaceLevelData.elevated,
child: MediaQuery( child: MediaQuery(
@ -331,7 +331,7 @@ class CupertinoAlertDialog extends StatelessWidget {
child: LayoutBuilder( child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) { builder: (BuildContext context, BoxConstraints constraints) {
return AnimatedPadding( return AnimatedPadding(
padding: MediaQuery.of(context).viewInsets + padding: MediaQuery.viewInsetsOf(context) +
const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0), const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
duration: insetAnimationDuration, duration: insetAnimationDuration,
curve: insetAnimationCurve, curve: insetAnimationCurve,
@ -611,12 +611,12 @@ class CupertinoActionSheet extends StatelessWidget {
if (cancelButton != null) _buildCancelButton(), if (cancelButton != null) _buildCancelButton(),
]; ];
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final double actionSheetWidth; final double actionSheetWidth;
if (orientation == Orientation.portrait) { if (orientation == Orientation.portrait) {
actionSheetWidth = MediaQuery.of(context).size.width - (_kActionSheetEdgeHorizontalPadding * 2); actionSheetWidth = MediaQuery.sizeOf(context).width - (_kActionSheetEdgeHorizontalPadding * 2);
} else { } else {
actionSheetWidth = MediaQuery.of(context).size.height - (_kActionSheetEdgeHorizontalPadding * 2); actionSheetWidth = MediaQuery.sizeOf(context).height - (_kActionSheetEdgeHorizontalPadding * 2);
} }
return SafeArea( return SafeArea(
@ -797,7 +797,7 @@ class _CupertinoDialogRenderWidget extends RenderObjectWidget {
@override @override
RenderObject createRenderObject(BuildContext context) { RenderObject createRenderObject(BuildContext context) {
return _RenderCupertinoDialog( return _RenderCupertinoDialog(
dividerThickness: _kDividerThickness / MediaQuery.of(context).devicePixelRatio, dividerThickness: _kDividerThickness / MediaQuery.devicePixelRatioOf(context),
isInAccessibilityMode: _isInAccessibilityMode(context) && !isActionSheet, isInAccessibilityMode: _isInAccessibilityMode(context) && !isActionSheet,
dividerColor: CupertinoDynamicColor.resolve(dividerColor, context), dividerColor: CupertinoDynamicColor.resolve(dividerColor, context),
isActionSheet: isActionSheet, isActionSheet: isActionSheet,
@ -1464,7 +1464,7 @@ class _CupertinoAlertActionSection extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double devicePixelRatio = MediaQuery.of(context).devicePixelRatio; final double devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
final List<Widget> interactiveButtons = <Widget>[]; final List<Widget> interactiveButtons = <Widget>[];
for (int i = 0; i < children.length; i += 1) { for (int i = 0; i < children.length; i += 1) {

View File

@ -347,7 +347,7 @@ class CupertinoListSection extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Color dividerColor = CupertinoColors.separator.resolveFrom(context); final Color dividerColor = CupertinoColors.separator.resolveFrom(context);
final double dividerHeight = 1.0 / MediaQuery.of(context).devicePixelRatio; final double dividerHeight = 1.0 / MediaQuery.devicePixelRatioOf(context);
// Long divider is used for wrapping the top and bottom of rows. // Long divider is used for wrapping the top and bottom of rows.
// Only used in CupertinoListSectionType.base mode. // Only used in CupertinoListSectionType.base mode.

View File

@ -174,7 +174,7 @@ class _CupertinoTextMagnifierState extends State<CupertinoTextMagnifier>
CupertinoMagnifier.kMagnifierAboveFocalPoint), CupertinoMagnifier.kMagnifierAboveFocalPoint),
); );
final Rect screenRect = Offset.zero & MediaQuery.of(context).size; final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context);
// Adjust the magnifier position so that it never exists outside the horizontal // Adjust the magnifier position so that it never exists outside the horizontal
// padding. // padding.

View File

@ -756,7 +756,7 @@ class _CupertinoSliverNavigationBarState extends State<CupertinoSliverNavigation
actionsForegroundColor: CupertinoTheme.of(context).primaryColor, actionsForegroundColor: CupertinoTheme.of(context).primaryColor,
transitionBetweenRoutes: widget.transitionBetweenRoutes, transitionBetweenRoutes: widget.transitionBetweenRoutes,
heroTag: widget.heroTag, heroTag: widget.heroTag,
persistentHeight: _kNavBarPersistentHeight + MediaQuery.of(context).padding.top, persistentHeight: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top,
alwaysShowMiddle: widget.alwaysShowMiddle && widget.middle != null, alwaysShowMiddle: widget.alwaysShowMiddle && widget.middle != null,
stretchConfiguration: widget.stretch ? OverScrollHeaderStretchConfiguration() : null, stretchConfiguration: widget.stretch ? OverScrollHeaderStretchConfiguration() : null,
), ),
@ -1104,7 +1104,7 @@ class _PersistentNavigationBar extends StatelessWidget {
} }
return SizedBox( return SizedBox(
height: _kNavBarPersistentHeight + MediaQuery.of(context).padding.top, height: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top,
child: SafeArea( child: SafeArea(
bottom: false, bottom: false,
child: paddedToolbar, child: paddedToolbar,
@ -1772,7 +1772,7 @@ class _NavigationBarTransition extends StatelessWidget {
// can actually be outside the linearly lerp'ed Rect in the middle of // can actually be outside the linearly lerp'ed Rect in the middle of
// the animation, such as the topLargeTitle. // the animation, such as the topLargeTitle.
return SizedBox( return SizedBox(
height: math.max(heightTween.begin!, heightTween.end!) + MediaQuery.of(context).padding.top, height: math.max(heightTween.begin!, heightTween.end!) + MediaQuery.paddingOf(context).top,
width: double.infinity, width: double.infinity,
child: Stack( child: Stack(
children: children, children: children,

View File

@ -690,8 +690,8 @@ class _CupertinoBackGestureDetectorState<T> extends State<_CupertinoBackGestureD
// For devices with notches, the drag area needs to be larger on the side // For devices with notches, the drag area needs to be larger on the side
// that has the notch. // that has the notch.
double dragAreaWidth = Directionality.of(context) == TextDirection.ltr ? double dragAreaWidth = Directionality.of(context) == TextDirection.ltr ?
MediaQuery.of(context).padding.left : MediaQuery.paddingOf(context).left :
MediaQuery.of(context).padding.right; MediaQuery.paddingOf(context).right;
dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth); dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth);
return Stack( return Stack(
fit: StackFit.passthrough, fit: StackFit.passthrough,

View File

@ -171,7 +171,7 @@ class _CupertinoScrollbarState extends RawScrollbarState<CupertinoScrollbar> {
..mainAxisMargin = _kScrollbarMainAxisMargin ..mainAxisMargin = _kScrollbarMainAxisMargin
..crossAxisMargin = _kScrollbarCrossAxisMargin ..crossAxisMargin = _kScrollbarCrossAxisMargin
..radius = _radius ..radius = _radius
..padding = MediaQuery.of(context).padding ..padding = MediaQuery.paddingOf(context)
..minLength = _kScrollbarMinLength ..minLength = _kScrollbarMinLength
..minOverscrollLength = _kScrollbarMinOverscrollLength ..minOverscrollLength = _kScrollbarMinOverscrollLength
..scrollbarOrientation = widget.scrollbarOrientation; ..scrollbarOrientation = widget.scrollbarOrientation;

View File

@ -1224,7 +1224,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField> with Restoratio
} }
final bool enabled = widget.enabled ?? true; final bool enabled = widget.enabled ?? true;
final Offset cursorOffset = Offset(_iOSHorizontalCursorOffsetPixels / MediaQuery.of(context).devicePixelRatio, 0); final Offset cursorOffset = Offset(_iOSHorizontalCursorOffsetPixels / MediaQuery.devicePixelRatioOf(context), 0);
final List<TextInputFormatter> formatters = <TextInputFormatter>[ final List<TextInputFormatter> formatters = <TextInputFormatter>[
...?widget.inputFormatters, ...?widget.inputFormatters,
if (widget.maxLength != null) if (widget.maxLength != null)

View File

@ -260,14 +260,14 @@ class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSe
} }
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context); final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
// The toolbar should appear below the TextField when there is not enough // The toolbar should appear below the TextField when there is not enough
// space above the TextField to show it, assuming there's always enough // space above the TextField to show it, assuming there's always enough
// space at the bottom in this case. // space at the bottom in this case.
final double anchorX = clampDouble(widget.selectionMidpoint.dx + widget.globalEditableRegion.left, final double anchorX = clampDouble(widget.selectionMidpoint.dx + widget.globalEditableRegion.left,
_kArrowScreenPadding + mediaQuery.padding.left, _kArrowScreenPadding + mediaQueryPadding.left,
mediaQuery.size.width - mediaQuery.padding.right - _kArrowScreenPadding, MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding,
); );
final double topAmountInEditableRegion = widget.endpoints.first.point.dy - widget.textLineHeight; final double topAmountInEditableRegion = widget.endpoints.first.point.dy - widget.textLineHeight;
@ -289,7 +289,7 @@ class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSe
final List<Widget> items = <Widget>[]; final List<Widget> items = <Widget>[];
final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
final Widget onePhysicalPixelVerticalDivider = final Widget onePhysicalPixelVerticalDivider =
SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio); SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context));
void addToolbarButton( void addToolbarButton(
String text, String text,

View File

@ -53,7 +53,7 @@ typedef CupertinoToolbarBuilder = Widget Function(
class _CupertinoToolbarButtonDivider extends StatelessWidget { class _CupertinoToolbarButtonDivider extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio); return SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context));
} }
} }
@ -132,9 +132,9 @@ class CupertinoTextSelectionToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context); final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
final double paddingAbove = mediaQuery.padding.top + _kToolbarScreenPadding; final double paddingAbove = mediaQueryPadding.top + _kToolbarScreenPadding;
final double toolbarHeightNeeded = paddingAbove final double toolbarHeightNeeded = paddingAbove
+ _kToolbarContentDistance + _kToolbarContentDistance
+ _kToolbarHeight; + _kToolbarHeight;
@ -142,8 +142,8 @@ class CupertinoTextSelectionToolbar extends StatelessWidget {
// The arrow, which points to the anchor, has some margin so it can't get // The arrow, which points to the anchor, has some margin so it can't get
// too close to the horizontal edges of the screen. // too close to the horizontal edges of the screen.
final double leftMargin = _kArrowScreenPadding + mediaQuery.padding.left; final double leftMargin = _kArrowScreenPadding + mediaQueryPadding.left;
final double rightMargin = mediaQuery.size.width - mediaQuery.padding.right - _kArrowScreenPadding; final double rightMargin = MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding;
final Offset anchorAboveAdjusted = Offset( final Offset anchorAboveAdjusted = Offset(
clampDouble(anchorAbove.dx, leftMargin, rightMargin), clampDouble(anchorAbove.dx, leftMargin, rightMargin),
@ -480,7 +480,7 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel
onPressed: _handlePreviousPage, onPressed: _handlePreviousPage,
text: '', text: '',
), ),
dividerWidth: 1.0 / MediaQuery.of(context).devicePixelRatio, dividerWidth: 1.0 / MediaQuery.devicePixelRatioOf(context),
nextButton: CupertinoTextSelectionToolbarButton.text( nextButton: CupertinoTextSelectionToolbarButton.text(
onPressed: _handleNextPage, onPressed: _handleNextPage,
text: '', text: '',

View File

@ -87,7 +87,7 @@ class CupertinoTheme extends StatelessWidget {
/// [MediaQueryData.platformBrightness] for descendant Cupertino widgets. /// [MediaQueryData.platformBrightness] for descendant Cupertino widgets.
static Brightness brightnessOf(BuildContext context) { static Brightness brightnessOf(BuildContext context) {
final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>(); final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>();
return inheritedTheme?.theme.data.brightness ?? MediaQuery.of(context).platformBrightness; return inheritedTheme?.theme.data.brightness ?? MediaQuery.platformBrightnessOf(context);
} }
/// Retrieves the [Brightness] to use for descendant Cupertino widgets, based /// Retrieves the [Brightness] to use for descendant Cupertino widgets, based
@ -107,7 +107,7 @@ class CupertinoTheme extends StatelessWidget {
/// [MediaQuery] exists, instead of returning null. /// [MediaQuery] exists, instead of returning null.
static Brightness? maybeBrightnessOf(BuildContext context) { static Brightness? maybeBrightnessOf(BuildContext context) {
final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>(); final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>();
return inheritedTheme?.theme.data.brightness ?? MediaQuery.maybeOf(context)?.platformBrightness; return inheritedTheme?.theme.data.brightness ?? MediaQuery.maybePlatformBrightnessOf(context);
} }
/// The widget below this widget in the tree. /// The widget below this widget in the tree.

View File

@ -976,7 +976,7 @@ const double _wideGutterSize = 24.0;
const double _narrowGutterSize = 12.0; const double _narrowGutterSize = 12.0;
double _getGutterSize(BuildContext context) => double _getGutterSize(BuildContext context) =>
MediaQuery.of(context).size.width >= _materialGutterThreshold ? _wideGutterSize : _narrowGutterSize; MediaQuery.sizeOf(context).width >= _materialGutterThreshold ? _wideGutterSize : _narrowGutterSize;
/// Signature for the builder callback used by [_MasterDetailFlow]. /// Signature for the builder callback used by [_MasterDetailFlow].
typedef _MasterViewBuilder = Widget Function(BuildContext context, bool isLateralUI); typedef _MasterViewBuilder = Widget Function(BuildContext context, bool isLateralUI);
@ -1463,7 +1463,7 @@ class _DetailView extends StatelessWidget {
if (_arguments == null) { if (_arguments == null) {
return const SizedBox.shrink(); return const SizedBox.shrink();
} }
final double screenHeight = MediaQuery.of(context).size.height; final double screenHeight = MediaQuery.sizeOf(context).height;
final double minHeight = (screenHeight - kToolbarHeight) / screenHeight; final double minHeight = (screenHeight - kToolbarHeight) / screenHeight;
return DraggableScrollableSheet( return DraggableScrollableSheet(

View File

@ -239,7 +239,7 @@ class _ActionChipDefaultsM3 extends ChipThemeData {
EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
} }

View File

@ -2097,7 +2097,7 @@ class _SliverAppBarState extends State<SliverAppBar> with TickerProviderStateMix
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(!widget.primary || debugCheckHasMediaQuery(context)); assert(!widget.primary || debugCheckHasMediaQuery(context));
final double bottomHeight = widget.bottom?.preferredSize.height ?? 0.0; final double bottomHeight = widget.bottom?.preferredSize.height ?? 0.0;
final double topPadding = widget.primary ? MediaQuery.of(context).padding.top : 0.0; final double topPadding = widget.primary ? MediaQuery.paddingOf(context).top : 0.0;
final double collapsedHeight = (widget.pinned && widget.floating && widget.bottom != null) final double collapsedHeight = (widget.pinned && widget.floating && widget.bottom != null)
? (widget.collapsedHeight ?? 0.0) + bottomHeight + topPadding ? (widget.collapsedHeight ?? 0.0) + bottomHeight + topPadding
: (widget.collapsedHeight ?? widget.toolbarHeight) + bottomHeight + topPadding; : (widget.collapsedHeight ?? widget.toolbarHeight) + bottomHeight + topPadding;
@ -2211,7 +2211,7 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
late final ThemeData theme = Theme.of(context); late final ThemeData theme = Theme.of(context);
final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!; final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!;
final double topPadding = primary ? MediaQuery.of(context).viewPadding.top : 0; final double topPadding = primary ? MediaQuery.viewPaddingOf(context).top : 0;
final double collapsedHeight = settings.minExtent - topPadding; final double collapsedHeight = settings.minExtent - topPadding;
final double scrollUnderHeight = settings.maxExtent - settings.minExtent; final double scrollUnderHeight = settings.maxExtent - settings.minExtent;
final _ScrollUnderFlexibleConfig config; final _ScrollUnderFlexibleConfig config;

View File

@ -293,7 +293,7 @@ class _MaterialBannerState extends State<MaterialBanner> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQueryData = MediaQuery.of(context); final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
assert(widget.actions.isNotEmpty); assert(widget.actions.isNotEmpty);
@ -399,7 +399,7 @@ class _MaterialBannerState extends State<MaterialBanner> {
onDismiss: () { onDismiss: () {
ScaffoldMessenger.of(context).removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss); ScaffoldMessenger.of(context).removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss);
}, },
child: mediaQueryData.accessibleNavigation child: accessibleNavigation
? materialBanner ? materialBanner
: SlideTransition( : SlideTransition(
position: slideOutAnimation, position: slideOutAnimation,
@ -408,7 +408,7 @@ class _MaterialBannerState extends State<MaterialBanner> {
); );
final Widget materialBannerTransition; final Widget materialBannerTransition;
if (mediaQueryData.accessibleNavigation) { if (accessibleNavigation) {
materialBannerTransition = materialBanner; materialBannerTransition = materialBanner;
} else { } else {
materialBannerTransition = AnimatedBuilder( materialBannerTransition = AnimatedBuilder(

View File

@ -607,8 +607,7 @@ class _Tile extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final MediaQueryData data = MediaQuery.of(context); if (MediaQuery.orientationOf(context) == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.linear) {
if (data.orientation == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.linear) {
return Align( return Align(
heightFactor: 1, heightFactor: 1,
child: Row( child: Row(
@ -1114,7 +1113,7 @@ class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerPr
final BottomNavigationBarLandscapeLayout layout = widget.landscapeLayout final BottomNavigationBarLandscapeLayout layout = widget.landscapeLayout
?? bottomTheme.landscapeLayout ?? bottomTheme.landscapeLayout
?? BottomNavigationBarLandscapeLayout.spread; ?? BottomNavigationBarLandscapeLayout.spread;
final double additionalBottomPadding = MediaQuery.of(context).viewPadding.bottom; final double additionalBottomPadding = MediaQuery.viewPaddingOf(context).bottom;
Color? backgroundColor; Color? backgroundColor;
switch (_effectiveType) { switch (_effectiveType) {
@ -1180,14 +1179,13 @@ class _Bar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final MediaQueryData data = MediaQuery.of(context);
Widget alignedChild = child; Widget alignedChild = child;
if (data.orientation == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.centered) { if (MediaQuery.orientationOf(context) == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.centered) {
alignedChild = Align( alignedChild = Align(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
heightFactor: 1, heightFactor: 1,
child: SizedBox( child: SizedBox(
width: data.size.height, width: MediaQuery.sizeOf(context).height,
child: child, child: child,
), ),
); );

View File

@ -409,7 +409,6 @@ class _ModalBottomSheetState<T> extends State<_ModalBottomSheet<T>> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context)); assert(debugCheckHasMaterialLocalizations(context));
final MediaQueryData mediaQuery = MediaQuery.of(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String routeLabel = _getRouteLabel(localizations); final String routeLabel = _getRouteLabel(localizations);
@ -436,7 +435,7 @@ class _ModalBottomSheetState<T> extends State<_ModalBottomSheet<T>> {
// Disable the initial animation when accessible navigation is on so // Disable the initial animation when accessible navigation is on so
// that the semantics are added to the tree at the correct time. // that the semantics are added to the tree at the correct time.
final double animationValue = animationCurve.transform( final double animationValue = animationCurve.transform(
mediaQuery.accessibleNavigation ? 1.0 : widget.route.animation!.value, MediaQuery.accessibleNavigationOf(context) ? 1.0 : widget.route.animation!.value,
); );
return Semantics( return Semantics(
scopesRoute: true, scopesRoute: true,

View File

@ -1158,7 +1158,7 @@ class _RawChipState extends State<RawChip> with MaterialStateMixin, TickerProvid
final EdgeInsetsGeometry defaultLabelPadding = EdgeInsets.lerp( final EdgeInsetsGeometry defaultLabelPadding = EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
@ -2257,7 +2257,7 @@ class _ChipDefaultsM3 extends ChipThemeData {
EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
} }

View File

@ -259,7 +259,7 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData {
EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
} }

View File

@ -425,7 +425,7 @@ class _DatePickerDialogState extends State<DatePickerDialog> with RestorationMix
} }
Size _dialogSize(BuildContext context) { Size _dialogSize(BuildContext context) {
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
switch (_entryMode.value) { switch (_entryMode.value) {
case DatePickerEntryMode.calendar: case DatePickerEntryMode.calendar:
case DatePickerEntryMode.calendarOnly: case DatePickerEntryMode.calendarOnly:
@ -456,11 +456,11 @@ class _DatePickerDialogState extends State<DatePickerDialog> with RestorationMix
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme; final ColorScheme colorScheme = theme.colorScheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final TextTheme textTheme = theme.textTheme; final TextTheme textTheme = theme.textTheme;
// Constrain the textScaleFactor to the largest supported value to prevent // Constrain the textScaleFactor to the largest supported value to prevent
// layout issues. // layout issues.
final double textScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 1.3); final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.3);
final String dateText = localizations.formatMediumDate(_selectedDate.value); final String dateText = localizations.formatMediumDate(_selectedDate.value);
final Color onPrimarySurface = colorScheme.brightness == Brightness.light final Color onPrimarySurface = colorScheme.brightness == Brightness.light
@ -1316,9 +1316,8 @@ class _DateRangePickerDialogState extends State<DateRangePickerDialog> with Rest
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final MediaQueryData mediaQuery = MediaQuery.of(context); final Orientation orientation = MediaQuery.orientationOf(context);
final Orientation orientation = mediaQuery.orientation; final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.3);
final double textScaleFactor = math.min(mediaQuery.textScaleFactor, 1.3);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final ColorScheme colors = Theme.of(context).colorScheme; final ColorScheme colors = Theme.of(context).colorScheme;
final Color onPrimarySurface = colors.brightness == Brightness.light final Color onPrimarySurface = colors.brightness == Brightness.light
@ -1367,7 +1366,7 @@ class _DateRangePickerDialogState extends State<DateRangePickerDialog> with Rest
: localizations.dateRangePickerHelpText.toUpperCase() : localizations.dateRangePickerHelpText.toUpperCase()
), ),
); );
size = mediaQuery.size; size = MediaQuery.sizeOf(context);
insetPadding = EdgeInsets.zero; insetPadding = EdgeInsets.zero;
shape = const RoundedRectangleBorder(); shape = const RoundedRectangleBorder();
elevation = 0; elevation = 0;
@ -1499,7 +1498,7 @@ class _CalendarRangePickerDialog extends StatelessWidget {
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme; final ColorScheme colorScheme = theme.colorScheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final TextTheme textTheme = theme.textTheme; final TextTheme textTheme = theme.textTheme;
final Color headerForeground = colorScheme.brightness == Brightness.light final Color headerForeground = colorScheme.brightness == Brightness.light
? colorScheme.onPrimary ? colorScheme.onPrimary
@ -1539,7 +1538,7 @@ class _CalendarRangePickerDialog extends StatelessWidget {
bottom: PreferredSize( bottom: PreferredSize(
preferredSize: const Size(double.infinity, 64), preferredSize: const Size(double.infinity, 64),
child: Row(children: <Widget>[ child: Row(children: <Widget>[
SizedBox(width: MediaQuery.of(context).size.width < 360 ? 42 : 72), SizedBox(width: MediaQuery.sizeOf(context).width < 360 ? 42 : 72),
Expanded( Expanded(
child: Semantics( child: Semantics(
label: '$helpText $startDateText to $endDateText', label: '$helpText $startDateText to $endDateText',
@ -2017,7 +2016,7 @@ class _DayHeaders extends StatelessWidget {
return Container( return Container(
constraints: BoxConstraints( constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).orientation == Orientation.landscape maxWidth: MediaQuery.orientationOf(context) == Orientation.landscape
? _maxCalendarWidthLandscape ? _maxCalendarWidthLandscape
: _maxCalendarWidthPortrait, : _maxCalendarWidthPortrait,
maxHeight: _monthItemRowHeight, maxHeight: _monthItemRowHeight,
@ -2469,7 +2468,7 @@ class _MonthItemState extends State<_MonthItem> {
paddedDayItems.addAll(weekList); paddedDayItems.addAll(weekList);
} }
final double maxWidth = MediaQuery.of(context).orientation == Orientation.landscape final double maxWidth = MediaQuery.orientationOf(context) == Orientation.landscape
? _maxCalendarWidthLandscape ? _maxCalendarWidthLandscape
: _maxCalendarWidthPortrait; : _maxCalendarWidthPortrait;
return Column( return Column(
@ -2623,7 +2622,7 @@ class _InputDateRangePickerDialog extends StatelessWidget {
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme; final ColorScheme colorScheme = theme.colorScheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final TextTheme textTheme = theme.textTheme; final TextTheme textTheme = theme.textTheme;
final Color onPrimarySurfaceColor = colorScheme.brightness == Brightness.light final Color onPrimarySurfaceColor = colorScheme.brightness == Brightness.light

View File

@ -177,12 +177,11 @@ class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelect
return const SizedBox.shrink(); return const SizedBox.shrink();
} }
final MediaQueryData mediaQuery = MediaQuery.of(context); final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
final Offset midpointAnchor = Offset( final Offset midpointAnchor = Offset(
clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left, clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left,
mediaQuery.padding.left, mediaQueryPadding.left,
mediaQuery.size.width - mediaQuery.padding.right, MediaQuery.sizeOf(context).width - mediaQueryPadding.right,
), ),
widget.selectionMidpoint.dy - widget.globalEditableRegion.top, widget.selectionMidpoint.dy - widget.globalEditableRegion.top,
); );

View File

@ -64,9 +64,8 @@ class DesktopTextSelectionToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context);
final double paddingAbove = mediaQuery.padding.top + _kToolbarScreenPadding; final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;
final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove); final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);
return Padding( return Padding(

View File

@ -217,7 +217,7 @@ class Dialog extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context); final DialogTheme dialogTheme = DialogTheme.of(context);
final EdgeInsets effectivePadding = MediaQuery.of(context).viewInsets + (insetPadding ?? EdgeInsets.zero); final EdgeInsets effectivePadding = MediaQuery.viewInsetsOf(context) + (insetPadding ?? EdgeInsets.zero);
final DialogTheme defaults = theme.useMaterial3 final DialogTheme defaults = theme.useMaterial3
? (_fullscreen ? _DialogFullscreenDefaultsM3(context) : _DialogDefaultsM3(context)) ? (_fullscreen ? _DialogFullscreenDefaultsM3(context) : _DialogDefaultsM3(context))
: _DialogDefaultsM2(context); : _DialogDefaultsM2(context);
@ -642,7 +642,7 @@ class AlertDialog extends StatelessWidget {
// The paddingScaleFactor is used to adjust the padding of Dialog's // The paddingScaleFactor is used to adjust the padding of Dialog's
// children. // children.
final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor); final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScaleFactorOf(context));
final TextDirection? textDirection = Directionality.maybeOf(context); final TextDirection? textDirection = Directionality.maybeOf(context);
Widget? iconWidget; Widget? iconWidget;
@ -1075,7 +1075,7 @@ class SimpleDialog extends StatelessWidget {
// The paddingScaleFactor is used to adjust the padding of Dialog // The paddingScaleFactor is used to adjust the padding of Dialog
// children. // children.
final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.of(context).textScaleFactor); final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScaleFactorOf(context));
final TextDirection? textDirection = Directionality.maybeOf(context); final TextDirection? textDirection = Directionality.maybeOf(context);
Widget? titleWidget; Widget? titleWidget;

View File

@ -382,11 +382,11 @@ class DrawerController extends StatefulWidget {
/// drawer. /// drawer.
/// ///
/// By default, the value used is 20.0 added to the padding edge of /// By default, the value used is 20.0 added to the padding edge of
/// `MediaQuery.of(context).padding` that corresponds to [alignment]. /// `MediaQuery.paddingOf(context)` that corresponds to [alignment].
/// This ensures that the drag area for notched devices is not obscured. For /// This ensures that the drag area for notched devices is not obscured. For
/// example, if [alignment] is set to [DrawerAlignment.start] and /// example, if [alignment] is set to [DrawerAlignment.start] and
/// `TextDirection.of(context)` is set to [TextDirection.ltr], /// `TextDirection.of(context)` is set to [TextDirection.ltr],
/// 20.0 will be added to `MediaQuery.of(context).padding.left`. /// 20.0 will be added to `MediaQuery.paddingOf(context).left`.
final double? edgeDragWidth; final double? edgeDragWidth;
/// Whether or not the drawer is opened or closed. /// Whether or not the drawer is opened or closed.
@ -680,7 +680,6 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
Widget _buildDrawer(BuildContext context) { Widget _buildDrawer(BuildContext context) {
final bool drawerIsStart = widget.alignment == DrawerAlignment.start; final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
final EdgeInsets padding = MediaQuery.of(context).padding;
final TextDirection textDirection = Directionality.of(context); final TextDirection textDirection = Directionality.of(context);
final bool isDesktop; final bool isDesktop;
switch (Theme.of(context).platform) { switch (Theme.of(context).platform) {
@ -698,6 +697,7 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
double? dragAreaWidth = widget.edgeDragWidth; double? dragAreaWidth = widget.edgeDragWidth;
if (widget.edgeDragWidth == null) { if (widget.edgeDragWidth == null) {
final EdgeInsets padding = MediaQuery.paddingOf(context);
switch (textDirection) { switch (textDirection) {
case TextDirection.ltr: case TextDirection.ltr:
dragAreaWidth = _kEdgeDragWidth + dragAreaWidth = _kEdgeDragWidth +

View File

@ -76,7 +76,7 @@ class DrawerHeader extends StatelessWidget {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final double statusBarHeight = MediaQuery.of(context).padding.top; final double statusBarHeight = MediaQuery.paddingOf(context).top;
return Container( return Container(
height: statusBarHeight + _kDrawerHeaderHeight, height: statusBarHeight + _kDrawerHeaderHeight,
margin: margin, margin: margin,

View File

@ -1333,7 +1333,7 @@ class _DropdownButtonState<T> extends State<DropdownButton<T>> with WidgetsBindi
// Similarly, we don't reduce the height of the button so much that its icon // Similarly, we don't reduce the height of the button so much that its icon
// would be clipped. // would be clipped.
double get _denseButtonHeight { double get _denseButtonHeight {
final double textScaleFactor = MediaQuery.of(context).textScaleFactor; final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!; final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!;
final double scaledFontSize = textScaleFactor * fontSize; final double scaledFontSize = textScaleFactor * fontSize;
return math.max(scaledFontSize, math.max(widget.iconSize, _kDenseButtonHeight)); return math.max(scaledFontSize, math.max(widget.iconSize, _kDenseButtonHeight));
@ -1369,7 +1369,7 @@ class _DropdownButtonState<T> extends State<DropdownButton<T>> with WidgetsBindi
bool get _enabled => widget.items != null && widget.items!.isNotEmpty && widget.onChanged != null; bool get _enabled => widget.items != null && widget.items!.isNotEmpty && widget.onChanged != null;
Orientation _getOrientation(BuildContext context) { Orientation _getOrientation(BuildContext context) {
Orientation? result = MediaQuery.maybeOf(context)?.orientation; Orientation? result = MediaQuery.maybeOrientationOf(context);
if (result == null) { if (result == null) {
// If there's no MediaQuery, then use the window aspect to determine // If there's no MediaQuery, then use the window aspect to determine
// orientation. // orientation.

View File

@ -252,7 +252,7 @@ class ElevatedButton extends ButtonStyleButton {
/// each state, and "others" means all other states. /// each state, and "others" means all other states.
/// ///
/// The `textScaleFactor` is the value of /// The `textScaleFactor` is the value of
/// `MediaQuery.of(context).textScaleFactor` and the names of the /// `MediaQuery.textScaleFactorOf(context)` and the names of the
/// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been
/// abbreviated for readability. /// abbreviated for readability.
/// ///
@ -394,7 +394,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) {
const EdgeInsets.symmetric(horizontal: 16), const EdgeInsets.symmetric(horizontal: 16),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
} }
@ -500,7 +500,7 @@ class _ElevatedButtonWithIcon extends ElevatedButton {
const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
return super.defaultStyleOf(context).copyWith( return super.defaultStyleOf(context).copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding), padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
@ -516,7 +516,7 @@ class _ElevatedButtonWithIconChild extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1; final double scale = MediaQuery.textScaleFactorOf(context);
final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;
return Row( return Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,

View File

@ -288,7 +288,7 @@ class FilledButton extends ButtonStyleButton {
/// each state, and "others" means all other states. /// each state, and "others" means all other states.
/// ///
/// The `textScaleFactor` is the value of /// The `textScaleFactor` is the value of
/// `MediaQuery.of(context).textScaleFactor` and the names of the /// `MediaQuery.textScaleFactorOf(context)` and the names of the
/// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been
/// abbreviated for readability. /// abbreviated for readability.
/// ///
@ -368,7 +368,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) {
const EdgeInsets.symmetric(horizontal: 16), const EdgeInsets.symmetric(horizontal: 16),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
} }
@ -471,7 +471,7 @@ class _FilledButtonWithIcon extends FilledButton {
const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
return super.defaultStyleOf(context).copyWith( return super.defaultStyleOf(context).copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding), padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
@ -487,7 +487,7 @@ class _FilledButtonWithIconChild extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1; final double scale = MediaQuery.textScaleFactorOf(context);
// Adjust the gap based on the text scale factor. Start at 8, and lerp // Adjust the gap based on the text scale factor. Start at 8, and lerp
// to 4 based on how large the text is. // to 4 based on how large the text is.
final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;

View File

@ -267,7 +267,7 @@ class _FilterChipDefaultsM3 extends ChipThemeData {
EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
} }

View File

@ -1018,7 +1018,7 @@ class _InkResponseState extends State<_InkResponseStateWidget>
} }
bool get _shouldShowFocus { bool get _shouldShowFocus {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return enabled && _hasFocus; return enabled && _hasFocus;
@ -1166,7 +1166,7 @@ class _InkResponseState extends State<_InkResponseStateWidget>
} }
bool get _canRequestFocus { bool get _canRequestFocus {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return enabled && widget.canRequestFocus; return enabled && widget.canRequestFocus;

View File

@ -310,7 +310,7 @@ class _InputChipDefaultsM3 extends ChipThemeData {
EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0), const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(MediaQuery.of(context).textScaleFactor - 1.0, 0.0, 1.0), clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0),
)!; )!;
} }

View File

@ -134,7 +134,7 @@ class _TextMagnifierState extends State<TextMagnifier> {
void _determineMagnifierPositionAndFocalPoint() { void _determineMagnifierPositionAndFocalPoint() {
final MagnifierInfo selectionInfo = final MagnifierInfo selectionInfo =
widget.magnifierInfo.value; widget.magnifierInfo.value;
final Rect screenRect = Offset.zero & MediaQuery.of(context).size; final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context);
// Since by default we draw at the top left corner, this offset // Since by default we draw at the top left corner, this offset
// shifts the magnifier so we draw at the center, and then also includes // shifts the magnifier so we draw at the center, and then also includes

View File

@ -315,7 +315,7 @@ class _MenuAnchorState extends State<MenuAnchor> {
_position?.isScrollingNotifier.removeListener(_handleScroll); _position?.isScrollingNotifier.removeListener(_handleScroll);
_position = Scrollable.maybeOf(context)?.position; _position = Scrollable.maybeOf(context)?.position;
_position?.isScrollingNotifier.addListener(_handleScroll); _position?.isScrollingNotifier.addListener(_handleScroll);
final Size newSize = MediaQuery.of(context).size; final Size newSize = MediaQuery.sizeOf(context);
if (_viewSize != null && newSize != _viewSize) { if (_viewSize != null && newSize != _viewSize) {
// Close the menus if the view changes size. // Close the menus if the view changes size.
_root._close(); _root._close();
@ -3746,7 +3746,7 @@ class _MenuButtonDefaultsM3 extends ButtonStyle {
const EdgeInsets.symmetric(horizontal: 12), const EdgeInsets.symmetric(horizontal: 12),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.maybeTextScaleFactorOf(context) ?? 1,
); );
} }
} }

View File

@ -994,7 +994,7 @@ class _ClampTextScaleFactor extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MediaQuery( return MediaQuery(
data: MediaQuery.of(context).copyWith( data: MediaQuery.of(context).copyWith(
textScaleFactor: clampDouble(MediaQuery.of(context).textScaleFactor, textScaleFactor: clampDouble(MediaQuery.textScaleFactorOf(context),
0.0, 0.0,
upperLimit, upperLimit,
), ),

View File

@ -351,7 +351,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) {
const EdgeInsets.symmetric(horizontal: 16), const EdgeInsets.symmetric(horizontal: 16),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
} }
@ -437,7 +437,7 @@ class _OutlinedButtonWithIconChild extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1; final double scale = MediaQuery.textScaleFactorOf(context);
final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;
return Row( return Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,

View File

@ -1292,7 +1292,7 @@ class PopupMenuButtonState<T> extends State<PopupMenuButton<T>> {
} }
bool get _canRequestFocus { bool get _canRequestFocus {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return widget.enabled; return widget.enabled;

View File

@ -619,7 +619,7 @@ class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin
// This size is used as the max bounds for the painting of the value // This size is used as the max bounds for the painting of the value
// indicators. It must be kept in sync with the function with the same name // indicators. It must be kept in sync with the function with the same name
// in slider.dart. // in slider.dart.
Size screenSize() => MediaQuery.of(context).size; Size screenSize() => MediaQuery.sizeOf(context);
return CompositedTransformTarget( return CompositedTransformTarget(
link: _layerLink, link: _layerLink,
@ -628,7 +628,7 @@ class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin
divisions: widget.divisions, divisions: widget.divisions,
labels: widget.labels, labels: widget.labels,
sliderTheme: sliderTheme, sliderTheme: sliderTheme,
textScaleFactor: MediaQuery.of(context).textScaleFactor, textScaleFactor: MediaQuery.textScaleFactorOf(context),
screenSize: screenSize(), screenSize: screenSize(),
onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null, onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null,
onChangeStart: widget.onChangeStart != null ? _handleDragStart : null, onChangeStart: widget.onChangeStart != null ? _handleDragStart : null,
@ -704,7 +704,7 @@ class _RangeSliderRenderObjectWidget extends LeafRenderObjectWidget {
textDirection: Directionality.of(context), textDirection: Directionality.of(context),
semanticFormatterCallback: semanticFormatterCallback, semanticFormatterCallback: semanticFormatterCallback,
platform: Theme.of(context).platform, platform: Theme.of(context).platform,
gestureSettings: MediaQuery.of(context).gestureSettings, gestureSettings: MediaQuery.gestureSettingsOf(context),
); );
} }
@ -726,7 +726,7 @@ class _RangeSliderRenderObjectWidget extends LeafRenderObjectWidget {
..textDirection = Directionality.of(context) ..textDirection = Directionality.of(context)
..semanticFormatterCallback = semanticFormatterCallback ..semanticFormatterCallback = semanticFormatterCallback
..platform = Theme.of(context).platform ..platform = Theme.of(context).platform
..gestureSettings = MediaQuery.of(context).gestureSettings; ..gestureSettings = MediaQuery.gestureSettingsOf(context);
} }
} }

View File

@ -191,18 +191,18 @@ class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProvide
@override @override
void didChangeDependencies() { void didChangeDependencies() {
final MediaQueryData mediaQuery = MediaQuery.of(context); final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
// If we transition from accessible navigation to non-accessible navigation // If we transition from accessible navigation to non-accessible navigation
// and there is a SnackBar that would have timed out that has already // and there is a SnackBar that would have timed out that has already
// completed its timer, dismiss that SnackBar. If the timer hasn't finished // completed its timer, dismiss that SnackBar. If the timer hasn't finished
// yet, let it timeout as normal. // yet, let it timeout as normal.
if ((_accessibleNavigation ?? false) if ((_accessibleNavigation ?? false)
&& !mediaQuery.accessibleNavigation && !accessibleNavigation
&& _snackBarTimer != null && _snackBarTimer != null
&& !_snackBarTimer!.isActive) { && !_snackBarTimer!.isActive) {
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout); hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
} }
_accessibleNavigation = mediaQuery.accessibleNavigation; _accessibleNavigation = accessibleNavigation;
super.didChangeDependencies(); super.didChangeDependencies();
} }
@ -568,8 +568,7 @@ class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProvide
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context); _accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
_accessibleNavigation = mediaQuery.accessibleNavigation;
if (_snackBars.isNotEmpty) { if (_snackBars.isNotEmpty) {
final ModalRoute<dynamic>? route = ModalRoute.of(context); final ModalRoute<dynamic>? route = ModalRoute.of(context);
@ -582,8 +581,7 @@ class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProvide
_snackBarController!.status == AnimationStatus.completed, _snackBarController!.status == AnimationStatus.completed,
); );
// Look up MediaQuery again in case the setting changed. // Look up MediaQuery again in case the setting changed.
final MediaQueryData mediaQuery = MediaQuery.of(context); if (snackBar.action != null && MediaQuery.accessibleNavigationOf(context)) {
if (mediaQuery.accessibleNavigation && snackBar.action != null) {
return; return;
} }
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout); hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
@ -1824,11 +1822,11 @@ class Scaffold extends StatefulWidget {
/// drawer. /// drawer.
/// ///
/// By default, the value used is 20.0 added to the padding edge of /// By default, the value used is 20.0 added to the padding edge of
/// `MediaQuery.of(context).padding` that corresponds to the surrounding /// `MediaQuery.paddingOf(context)` that corresponds to the surrounding
/// [TextDirection]. This ensures that the drag area for notched devices is /// [TextDirection]. This ensures that the drag area for notched devices is
/// not obscured. For example, if `TextDirection.of(context)` is set to /// not obscured. For example, if `TextDirection.of(context)` is set to
/// [TextDirection.ltr], 20.0 will be added to /// [TextDirection.ltr], 20.0 will be added to
/// `MediaQuery.of(context).padding.left`. /// `MediaQuery.paddingOf(context).left`.
final double? drawerEdgeDragWidth; final double? drawerEdgeDragWidth;
/// Determines if the [Scaffold.drawer] can be opened with a drag /// Determines if the [Scaffold.drawer] can be opened with a drag
@ -2761,7 +2759,6 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasDirectionality(context)); assert(debugCheckHasDirectionality(context));
final MediaQueryData mediaQuery = MediaQuery.of(context);
final ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
final TextDirection textDirection = Directionality.of(context); final TextDirection textDirection = Directionality.of(context);
@ -2796,7 +2793,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
} }
if (widget.appBar != null) { if (widget.appBar != null) {
final double topPadding = widget.primary ? mediaQuery.padding.top : 0.0; final double topPadding = widget.primary ? MediaQuery.paddingOf(context).top : 0.0;
_appBarMaxHeight = AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding; _appBarMaxHeight = AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding;
assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite); assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite);
_addIfNonNull( _addIfNonNull(
@ -2973,14 +2970,14 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
} }
// The minimum insets for contents of the Scaffold to keep visible. // The minimum insets for contents of the Scaffold to keep visible.
final EdgeInsets minInsets = mediaQuery.padding.copyWith( final EdgeInsets minInsets = MediaQuery.paddingOf(context).copyWith(
bottom: _resizeToAvoidBottomInset ? mediaQuery.viewInsets.bottom : 0.0, bottom: _resizeToAvoidBottomInset ? MediaQuery.viewInsetsOf(context).bottom : 0.0,
); );
// The minimum viewPadding for interactive elements positioned by the // The minimum viewPadding for interactive elements positioned by the
// Scaffold to keep within safe interactive areas. // Scaffold to keep within safe interactive areas.
final EdgeInsets minViewPadding = mediaQuery.viewPadding.copyWith( final EdgeInsets minViewPadding = MediaQuery.viewPaddingOf(context).copyWith(
bottom: _resizeToAvoidBottomInset && mediaQuery.viewInsets.bottom != 0.0 ? 0.0 : null, bottom: _resizeToAvoidBottomInset && MediaQuery.viewInsetsOf(context).bottom != 0.0 ? 0.0 : null,
); );
// extendBody locked when keyboard is open // extendBody locked when keyboard is open

View File

@ -427,7 +427,7 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> {
..crossAxisMargin = _scrollbarTheme.crossAxisMargin ?? (_useAndroidScrollbar ? 0.0 : _kScrollbarMargin) ..crossAxisMargin = _scrollbarTheme.crossAxisMargin ?? (_useAndroidScrollbar ? 0.0 : _kScrollbarMargin)
..mainAxisMargin = _scrollbarTheme.mainAxisMargin ?? 0.0 ..mainAxisMargin = _scrollbarTheme.mainAxisMargin ?? 0.0
..minLength = _scrollbarTheme.minThumbLength ?? _kScrollbarMinLength ..minLength = _scrollbarTheme.minThumbLength ?? _kScrollbarMinLength
..padding = MediaQuery.of(context).padding ..padding = MediaQuery.paddingOf(context)
..scrollbarOrientation = widget.scrollbarOrientation ..scrollbarOrientation = widget.scrollbarOrientation
..ignorePointer = !enableGestures; ..ignorePointer = !enableGestures;
} }

View File

@ -659,7 +659,7 @@ class _SelectableTextState extends State<SelectableText> implements TextSelectio
cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor;
selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
cursorRadius ??= const Radius.circular(2.0); cursorRadius ??= const Radius.circular(2.0);
cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0);
break; break;
case TargetPlatform.macOS: case TargetPlatform.macOS:
@ -671,7 +671,7 @@ class _SelectableTextState extends State<SelectableText> implements TextSelectio
cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor;
selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
cursorRadius ??= const Radius.circular(2.0); cursorRadius ??= const Radius.circular(2.0);
cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0);
break; break;
case TargetPlatform.android: case TargetPlatform.android:
@ -700,7 +700,7 @@ class _SelectableTextState extends State<SelectableText> implements TextSelectio
if (effectiveTextStyle == null || effectiveTextStyle.inherit) { if (effectiveTextStyle == null || effectiveTextStyle.inherit) {
effectiveTextStyle = defaultTextStyle.style.merge(widget.style ?? _controller._textSpan.style); effectiveTextStyle = defaultTextStyle.style.merge(widget.style ?? _controller._textSpan.style);
} }
if (MediaQuery.boldTextOverride(context)) { if (MediaQuery.boldTextOf(context)) {
effectiveTextStyle = effectiveTextStyle.merge(const TextStyle(fontWeight: FontWeight.bold)); effectiveTextStyle = effectiveTextStyle.merge(const TextStyle(fontWeight: FontWeight.bold));
} }
final Widget child = RepaintBoundary( final Widget child = RepaintBoundary(

View File

@ -826,7 +826,7 @@ class _SliderState extends State<Slider> with TickerProviderStateMixin {
// This size is used as the max bounds for the painting of the value // This size is used as the max bounds for the painting of the value
// indicators It must be kept in sync with the function with the same name // indicators It must be kept in sync with the function with the same name
// in range_slider.dart. // in range_slider.dart.
Size screenSize() => MediaQuery.of(context).size; Size screenSize() => MediaQuery.sizeOf(context);
VoidCallback? handleDidGainAccessibilityFocus; VoidCallback? handleDidGainAccessibilityFocus;
switch (theme.platform) { switch (theme.platform) {
@ -847,7 +847,7 @@ class _SliderState extends State<Slider> with TickerProviderStateMixin {
} }
final Map<ShortcutActivator, Intent> shortcutMap; final Map<ShortcutActivator, Intent> shortcutMap;
switch (MediaQuery.of(context).navigationMode) { switch (MediaQuery.navigationModeOf(context)) {
case NavigationMode.directional: case NavigationMode.directional:
shortcutMap = _directionalNavShortcutMap; shortcutMap = _directionalNavShortcutMap;
break; break;
@ -861,8 +861,8 @@ class _SliderState extends State<Slider> with TickerProviderStateMixin {
// This needs to be updated when accessibility // This needs to be updated when accessibility
// guidelines are available on the material specs page // guidelines are available on the material specs page
// https://m3.material.io/components/sliders/accessibility. // https://m3.material.io/components/sliders/accessibility.
? math.min(MediaQuery.of(context).textScaleFactor, 1.3) ? math.min(MediaQuery.textScaleFactorOf(context), 1.3)
: MediaQuery.of(context).textScaleFactor; : MediaQuery.textScaleFactorOf(context);
return Semantics( return Semantics(
container: true, container: true,
@ -994,7 +994,7 @@ class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
platform: Theme.of(context).platform, platform: Theme.of(context).platform,
hasFocus: hasFocus, hasFocus: hasFocus,
hovering: hovering, hovering: hovering,
gestureSettings: MediaQuery.of(context).gestureSettings, gestureSettings: MediaQuery.gestureSettingsOf(context),
); );
} }
@ -1018,7 +1018,7 @@ class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
..platform = Theme.of(context).platform ..platform = Theme.of(context).platform
..hasFocus = hasFocus ..hasFocus = hasFocus
..hovering = hovering ..hovering = hovering
..gestureSettings = MediaQuery.of(context).gestureSettings; ..gestureSettings = MediaQuery.gestureSettingsOf(context);
// Ticker provider cannot change since there's a 1:1 relationship between // Ticker provider cannot change since there's a 1:1 relationship between
// the _SliderRenderObjectWidget object and the _SliderState object. // the _SliderRenderObjectWidget object and the _SliderState object.
} }

View File

@ -485,7 +485,7 @@ class _SnackBarState extends State<SnackBar> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQueryData = MediaQuery.of(context); final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
assert(widget.animation != null); assert(widget.animation != null);
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme; final ColorScheme colorScheme = theme.colorScheme;
@ -599,7 +599,7 @@ class _SnackBarState extends State<SnackBar> {
final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!; final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!;
final double snackBarWidth = widget.width ?? mediaQueryData.size.width - (margin.left + margin.right); final double snackBarWidth = widget.width ?? MediaQuery.sizeOf(context).width - (margin.left + margin.right);
// Action and Icon will overflow to a new line if their width is greater // Action and Icon will overflow to a new line if their width is greater
// than one quarter of the total Snack Bar width. // than one quarter of the total Snack Bar width.
final bool actionLineOverflow = final bool actionLineOverflow =
@ -675,7 +675,7 @@ class _SnackBarState extends State<SnackBar> {
color: backgroundColor, color: backgroundColor,
child: Theme( child: Theme(
data: effectiveTheme, data: effectiveTheme,
child: mediaQueryData.accessibleNavigation || theme.useMaterial3 child: accessibleNavigation || theme.useMaterial3
? snackBar ? snackBar
: FadeTransition( : FadeTransition(
opacity: fadeOutAnimation, opacity: fadeOutAnimation,
@ -723,7 +723,7 @@ class _SnackBarState extends State<SnackBar> {
); );
final Widget snackBarTransition; final Widget snackBarTransition;
if (mediaQueryData.accessibleNavigation) { if (accessibleNavigation) {
snackBarTransition = snackBar; snackBarTransition = snackBar;
} else if (isFloatingSnackBar && !theme.useMaterial3) { } else if (isFloatingSnackBar && !theme.useMaterial3) {
snackBarTransition = FadeTransition( snackBarTransition = FadeTransition(

View File

@ -249,7 +249,7 @@ class TextButton extends ButtonStyleButton {
/// each state and "others" means all other states. /// each state and "others" means all other states.
/// ///
/// The `textScaleFactor` is the value of /// The `textScaleFactor` is the value of
/// `MediaQuery.of(context).textScaleFactor` and the names of the /// `MediaQuery.textScaleFactorOf(context)` and the names of the
/// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been
/// abbreviated for readability. /// abbreviated for readability.
/// ///
@ -382,7 +382,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) {
const EdgeInsets.all(8), const EdgeInsets.all(8),
const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
} }
@ -495,7 +495,7 @@ class _TextButtonWithIcon extends TextButton {
const EdgeInsets.all(8), const EdgeInsets.all(8),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4),
MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, MediaQuery.textScaleFactorOf(context),
); );
return super.defaultStyleOf(context).copyWith( return super.defaultStyleOf(context).copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding), padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
@ -514,7 +514,7 @@ class _TextButtonWithIconChild extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double scale = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1; final double scale = MediaQuery.textScaleFactorOf(context);
final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!;
return Row( return Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,

View File

@ -967,7 +967,7 @@ class _TextFieldState extends State<TextField> with RestorationMixin implements
} }
bool get _canRequestFocus { bool get _canRequestFocus {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return _isEnabled; return _isEnabled;
@ -1215,7 +1215,7 @@ class _TextFieldState extends State<TextField> with RestorationMixin implements
cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor;
selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
cursorRadius ??= const Radius.circular(2.0); cursorRadius ??= const Radius.circular(2.0);
cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0);
autocorrectionTextRectColor = selectionColor; autocorrectionTextRectColor = selectionColor;
break; break;
@ -1228,7 +1228,7 @@ class _TextFieldState extends State<TextField> with RestorationMixin implements
cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor;
selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
cursorRadius ??= const Radius.circular(2.0); cursorRadius ??= const Radius.circular(2.0);
cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0);
handleDidGainAccessibilityFocus = () { handleDidGainAccessibilityFocus = () {
// Automatically activate the TextField when it receives accessibility focus. // Automatically activate the TextField when it receives accessibility focus.
if (!_effectiveFocusNode.hasFocus && _effectiveFocusNode.canRequestFocus) { if (!_effectiveFocusNode.hasFocus && _effectiveFocusNode.canRequestFocus) {

View File

@ -99,7 +99,7 @@ class TextSelectionToolbar extends StatelessWidget {
final Offset anchorBelowPadded = final Offset anchorBelowPadded =
anchorBelow + const Offset(0.0, _kToolbarContentDistanceBelow); anchorBelow + const Offset(0.0, _kToolbarContentDistanceBelow);
final double paddingAbove = MediaQuery.of(context).padding.top final double paddingAbove = MediaQuery.paddingOf(context).top
+ _kToolbarScreenPadding; + _kToolbarScreenPadding;
final double availableHeight = anchorAbovePadded.dy - _kToolbarContentDistance - paddingAbove; final double availableHeight = anchorAbovePadded.dy - _kToolbarContentDistance - paddingAbove;
final bool fitsAbove = _kToolbarHeight <= availableHeight; final bool fitsAbove = _kToolbarHeight <= availableHeight;

View File

@ -108,7 +108,7 @@ class TimeOfDay {
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
return localizations.formatTimeOfDay( return localizations.formatTimeOfDay(
this, this,
alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context),
); );
} }

View File

@ -149,7 +149,7 @@ class _TimePickerHeader extends StatelessWidget {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat( final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(
alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context),
); );
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String timePickerDialHelpText = themeData.useMaterial3 final String timePickerDialHelpText = themeData.useMaterial3
@ -339,7 +339,7 @@ class _HourControl extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String formattedHour = localizations.formatHour( final String formattedHour = localizations.formatHour(
fragmentContext.selectedTime, fragmentContext.selectedTime,
@ -581,7 +581,7 @@ class _DayPeriodControl extends StatelessWidget {
side: borderSide, side: borderSide,
); );
final double buttonTextScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 2.0); final double buttonTextScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 2.0);
final Widget amButton = Material( final Widget amButton = Material(
color: MaterialStateProperty.resolveAs(backgroundColor, amStates), color: MaterialStateProperty.resolveAs(backgroundColor, amStates),
@ -990,7 +990,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
late ThemeData themeData; late ThemeData themeData;
late MaterialLocalizations localizations; late MaterialLocalizations localizations;
late MediaQueryData media; late bool alwaysUse24HourFormat;
_DialPainter? painter; _DialPainter? painter;
@override @override
@ -999,7 +999,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
themeData = Theme.of(context); themeData = Theme.of(context);
localizations = MaterialLocalizations.of(context); localizations = MaterialLocalizations.of(context);
media = MediaQuery.of(context); alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context);
} }
@override @override
@ -1209,7 +1209,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
_TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, int value, String label, VoidCallback onTap) { _TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, int value, String label, VoidCallback onTap) {
final TextStyle style = textTheme.bodyLarge!.copyWith(color: color); final TextStyle style = textTheme.bodyLarge!.copyWith(color: color);
final double labelScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 2.0); final double labelScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 2.0);
return _TappableLabel( return _TappableLabel(
value: value, value: value,
painter: TextPainter( painter: TextPainter(
@ -1227,7 +1227,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
textTheme, textTheme,
color, color,
timeOfDay.hour, timeOfDay.hour,
localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat), localizations.formatHour(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat),
() { () {
_selectHour(timeOfDay.hour); _selectHour(timeOfDay.hour);
}, },
@ -1240,7 +1240,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
textTheme, textTheme,
color, color,
timeOfDay.hour, timeOfDay.hour,
localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat), localizations.formatHour(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat),
() { () {
_selectHour(timeOfDay.hour); _selectHour(timeOfDay.hour);
}, },
@ -1406,7 +1406,7 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi
return null; return null;
} }
if (MediaQuery.of(context).alwaysUse24HourFormat) { if (MediaQuery.alwaysUse24HourFormatOf(context)) {
if (newHour >= 0 && newHour < 24) { if (newHour >= 0 && newHour < 24) {
return newHour; return newHour;
} }
@ -1494,8 +1494,7 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData media = MediaQuery.of(context); final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context));
final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final TextStyle hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? theme.textTheme.displayMedium!; final TextStyle hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? theme.textTheme.displayMedium!;
@ -1759,7 +1758,7 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora
} }
String get _formattedValue { String get _formattedValue {
final bool alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour( return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour(
widget.selectedTime, widget.selectedTime,
@ -1805,7 +1804,7 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora
// //
// TODO(rami-a): Once https://github.com/flutter/flutter/issues/67571 is // TODO(rami-a): Once https://github.com/flutter/flutter/issues/67571 is
// resolved, remove the window check for semantics being enabled on web. // resolved, remove the window check for semantics being enabled on web.
final String? hintText = MediaQuery.of(context).accessibleNavigation || WidgetsBinding.instance.window.semanticsEnabled final String? hintText = MediaQuery.accessibleNavigationOf(context) || WidgetsBinding.instance.window.semanticsEnabled
? widget.semanticHintText ? widget.semanticHintText
: (focusNode.hasFocus ? null : _formattedValue); : (focusNode.hasFocus ? null : _formattedValue);
inputDecoration = inputDecoration.copyWith( inputDecoration = inputDecoration.copyWith(
@ -2146,11 +2145,10 @@ class _TimePickerDialogState extends State<TimePickerDialog> with RestorationMix
return; return;
} }
final MediaQueryData media = MediaQuery.of(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
_announceToAccessibility( _announceToAccessibility(
context, context,
localizations.formatTimeOfDay(widget.initialTime, alwaysUse24HourFormat: media.alwaysUse24HourFormat), localizations.formatTimeOfDay(widget.initialTime, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)),
); );
_announcedInitialTime.value = true; _announcedInitialTime.value = true;
} }
@ -2195,12 +2193,12 @@ class _TimePickerDialogState extends State<TimePickerDialog> with RestorationMix
} }
Size _dialogSize(BuildContext context) { Size _dialogSize(BuildContext context) {
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
// Constrain the textScaleFactor to prevent layout issues. Since only some // Constrain the textScaleFactor to prevent layout issues. Since only some
// parts of the time picker scale up with textScaleFactor, we cap the factor // parts of the time picker scale up with textScaleFactor, we cap the factor
// to 1.1 as that provides enough space to reasonably fit all the content. // to 1.1 as that provides enough space to reasonably fit all the content.
final double textScaleFactor = math.min(MediaQuery.of(context).textScaleFactor, 1.1); final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.1);
final double timePickerWidth; final double timePickerWidth;
final double timePickerHeight; final double timePickerHeight;
@ -2234,12 +2232,11 @@ class _TimePickerDialogState extends State<TimePickerDialog> with RestorationMix
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData media = MediaQuery.of(context); final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context));
final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat);
final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h;
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final ShapeBorder shape = TimePickerTheme.of(context).shape ?? _kDefaultShape; final ShapeBorder shape = TimePickerTheme.of(context).shape ?? _kDefaultShape;
final Orientation orientation = media.orientation; final Orientation orientation = MediaQuery.orientationOf(context);
final Widget actions = Row( final Widget actions = Row(
children: <Widget>[ children: <Widget>[

View File

@ -884,7 +884,7 @@ class _TooltipOverlay extends StatelessWidget {
); );
} }
return Positioned.fill( return Positioned.fill(
bottom: MediaQuery.maybeOf(context)?.viewInsets.bottom ?? 0.0, bottom: MediaQuery.maybeViewInsetsOf(context)?.bottom ?? 0.0,
child: CustomSingleChildLayout( child: CustomSingleChildLayout(
delegate: _TooltipPositionDelegate( delegate: _TooltipPositionDelegate(
target: target, target: target,

View File

@ -1230,7 +1230,7 @@ class _FocusableActionDetectorState extends State<FocusableActionDetector> {
} }
bool canRequestFocus(FocusableActionDetector target) { bool canRequestFocus(FocusableActionDetector target) {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return target.enabled; return target.enabled;
@ -1271,7 +1271,7 @@ class _FocusableActionDetectorState extends State<FocusableActionDetector> {
} }
bool get _canRequestFocus { bool get _canRequestFocus {
final NavigationMode mode = MediaQuery.maybeOf(context)?.navigationMode ?? NavigationMode.traditional; final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional;
switch (mode) { switch (mode) {
case NavigationMode.traditional: case NavigationMode.traditional:
return widget.enabled; return widget.enabled;

View File

@ -447,7 +447,7 @@ class _DraggableState<T extends Object> extends State<Draggable<T>> {
@override @override
void didChangeDependencies() { void didChangeDependencies() {
_recognizer!.gestureSettings = MediaQuery.maybeOf(context)?.gestureSettings; _recognizer!.gestureSettings = MediaQuery.maybeGestureSettingsOf(context);
super.didChangeDependencies(); super.didChangeDependencies();
} }

View File

@ -2409,7 +2409,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
} }
// Hide the text selection toolbar on mobile when orientation changes. // Hide the text selection toolbar on mobile when orientation changes.
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
if (_lastOrientation == null) { if (_lastOrientation == null) {
_lastOrientation = orientation; _lastOrientation = orientation;
return; return;
@ -3583,7 +3583,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
@override @override
TextEditingValue get textEditingValue => _value; TextEditingValue get textEditingValue => _value;
double get _devicePixelRatio => MediaQuery.of(context).devicePixelRatio; double get _devicePixelRatio => MediaQuery.devicePixelRatioOf(context);
@override @override
void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause? cause) { void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause? cause) {

View File

@ -1017,7 +1017,7 @@ class GestureDetector extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{}; final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{};
final DeviceGestureSettings? gestureSettings = MediaQuery.maybeOf(context)?.gestureSettings; final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context);
if (onTapDown != null || if (onTapDown != null ||
onTapUp != null || onTapUp != null ||

View File

@ -53,7 +53,7 @@ export 'package:flutter/painting.dart' show
ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size? size }) { ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size? size }) {
return ImageConfiguration( return ImageConfiguration(
bundle: DefaultAssetBundle.of(context), bundle: DefaultAssetBundle.of(context),
devicePixelRatio: MediaQuery.maybeOf(context)?.devicePixelRatio ?? 1.0, devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0,
locale: Localizations.maybeLocaleOf(context), locale: Localizations.maybeLocaleOf(context),
textDirection: Directionality.maybeOf(context), textDirection: Directionality.maybeOf(context),
size: size, size: size,
@ -1106,7 +1106,7 @@ class _ImageState extends State<Image> with WidgetsBindingObserver {
} }
void _updateInvertColors() { void _updateInvertColors() {
_invertColors = MediaQuery.maybeOf(context)?.invertColors _invertColors = MediaQuery.maybeInvertColorsOf(context)
?? SemanticsBinding.instance.accessibilityFeatures.invertColors; ?? SemanticsBinding.instance.accessibilityFeatures.invertColors;
} }

View File

@ -12,6 +12,7 @@ import 'basic.dart';
import 'binding.dart'; import 'binding.dart';
import 'debug.dart'; import 'debug.dart';
import 'framework.dart'; import 'framework.dart';
import 'inherited_model.dart';
// Examples can assume: // Examples can assume:
// late BuildContext context; // late BuildContext context;
@ -25,6 +26,52 @@ enum Orientation {
landscape landscape
} }
/// Specifies a part of MediaQueryData to depend on.
///
/// [MediaQuery] contains a large number of related properties. Widgets frequently
/// depend on only a few of these attributes. For example, a widget that needs to
/// rebuild when the [MediaQueryData.textScaleFactor] changes does not need to
/// be notified when the [MediaQueryData.size] changes. Specifying an aspect avoids
/// unnecessary rebuilds.
enum _MediaQueryAspect {
/// Specifies the aspect corresponding to [MediaQueryData.size].
size,
/// Specifies the aspect corresponding to [MediaQueryData.orientation].
orientation,
/// Specifies the aspect corresponding to [MediaQueryData.devicePixelRatio].
devicePixelRatio,
/// Specifies the aspect corresponding to [MediaQueryData.textScaleFactor].
textScaleFactor,
/// Specifies the aspect corresponding to [MediaQueryData.platformBrightness].
platformBrightness,
/// Specifies the aspect corresponding to [MediaQueryData.padding].
padding,
/// Specifies the aspect corresponding to [MediaQueryData.viewInsets].
viewInsets,
/// Specifies the aspect corresponding to [MediaQueryData.systemGestureInsets].
systemGestureInsets,
/// Specifies the aspect corresponding to [MediaQueryData.viewPadding].
viewPadding,
/// Specifies the aspect corresponding to [MediaQueryData.alwaysUse24HourFormat].
alwaysUse24HourFormat,
/// Specifies the aspect corresponding to [MediaQueryData.accessibleNavigation].
accessibleNavigation,
/// Specifies the aspect corresponding to [MediaQueryData.invertColors].
invertColors,
/// Specifies the aspect corresponding to [MediaQueryData.highContrast].
highContrast,
/// Specifies the aspect corresponding to [MediaQueryData.disableAnimations].
disableAnimations,
/// Specifies the aspect corresponding to [MediaQueryData.boldText].
boldText,
/// Specifies the aspect corresponding to [MediaQueryData.navigationMode].
navigationMode,
/// Specifies the aspect corresponding to [MediaQueryData.gestureSettings].
gestureSettings,
/// Specifies the aspect corresponding to [MediaQueryData.displayFeatures].
displayFeatures,
}
/// Information about a piece of media (e.g., a window). /// Information about a piece of media (e.g., a window).
/// ///
/// For example, the [MediaQueryData.size] property contains the width and /// For example, the [MediaQueryData.size] property contains the width and
@ -178,6 +225,8 @@ class MediaQueryData {
/// See also: /// See also:
/// ///
/// * [FlutterView.physicalSize], which returns the size in physical pixels. /// * [FlutterView.physicalSize], which returns the size in physical pixels.
/// * [MediaQuery.sizeOf], a method to find and depend on the size defined
/// for a [BuildContext].
final Size size; final Size size;
/// The number of device pixels for each logical pixel. This number might not /// The number of device pixels for each logical pixel. This number might not
@ -192,7 +241,7 @@ class MediaQueryData {
/// ///
/// See also: /// See also:
/// ///
/// * [MediaQuery.textScaleFactorOf], a convenience method which returns the /// * [MediaQuery.textScaleFactorOf], a method to find and depend on the
/// textScaleFactor defined for a [BuildContext]. /// textScaleFactor defined for a [BuildContext].
final double textScaleFactor; final double textScaleFactor;
@ -203,6 +252,11 @@ class MediaQueryData {
/// ///
/// Not all platforms necessarily support a concept of brightness mode. Those /// Not all platforms necessarily support a concept of brightness mode. Those
/// platforms will report [Brightness.light] in this property. /// platforms will report [Brightness.light] in this property.
///
/// See also:
///
/// * [MediaQuery.platformBrightnessOf], a method to find and depend on the
/// platformBrightness defined for a [BuildContext].
final Brightness platformBrightness; final Brightness platformBrightness;
/// The parts of the display that are completely obscured by system UI, /// The parts of the display that are completely obscured by system UI,
@ -690,7 +744,7 @@ class MediaQueryData {
/// * [WidgetsApp] and [MaterialApp], which introduce a [MediaQuery] and keep /// * [WidgetsApp] and [MaterialApp], which introduce a [MediaQuery] and keep
/// it up to date with the current screen metrics as they change. /// it up to date with the current screen metrics as they change.
/// * [MediaQueryData], the data structure that represents the metrics. /// * [MediaQueryData], the data structure that represents the metrics.
class MediaQuery extends InheritedWidget { class MediaQuery extends InheritedModel<_MediaQueryAspect> {
/// Creates a widget that provides [MediaQueryData] to its descendants. /// Creates a widget that provides [MediaQueryData] to its descendants.
/// ///
/// The [data] and [child] arguments must not be null. /// The [data] and [child] arguments must not be null.
@ -873,6 +927,11 @@ class MediaQuery extends InheritedWidget {
/// examples). When that information changes, your widget will be scheduled to /// examples). When that information changes, your widget will be scheduled to
/// be rebuilt, keeping your widget up-to-date. /// be rebuilt, keeping your widget up-to-date.
/// ///
/// If the widget only requires a subset of properties of the [MediaQueryData]
/// object, it is preferred to use the specific methods (for example:
/// [MediaQuery.sizeOf] and [MediaQuery.paddingOf]), as those methods will not
/// cause a widget to rebuild when unrelated properties are updated.
///
/// Typical usage is as follows: /// Typical usage is as follows:
/// ///
/// ```dart /// ```dart
@ -889,8 +948,12 @@ class MediaQuery extends InheritedWidget {
/// [MediaQuery] ancestor, it returns null instead. /// [MediaQuery] ancestor, it returns null instead.
static MediaQueryData of(BuildContext context) { static MediaQueryData of(BuildContext context) {
assert(context != null); assert(context != null);
return _of(context);
}
static MediaQueryData _of(BuildContext context, [_MediaQueryAspect? aspect]) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
return context.dependOnInheritedWidgetOfExactType<MediaQuery>()!.data; return InheritedModel.inheritFrom<MediaQuery>(context, aspect: aspect)!.data;
} }
/// The data from the closest instance of this class that encloses the given /// The data from the closest instance of this class that encloses the given
@ -907,6 +970,11 @@ class MediaQuery extends InheritedWidget {
/// examples). When that information changes, your widget will be scheduled to /// examples). When that information changes, your widget will be scheduled to
/// be rebuilt, keeping your widget up-to-date. /// be rebuilt, keeping your widget up-to-date.
/// ///
/// If the widget only requires a subset of properties of the [MediaQueryData]
/// object, it is preferred to use the specific methods (for example:
/// [MediaQuery.maybeSizeOf] and [MediaQuery.maybePaddingOf]), as those methods
/// will not cause a widget to rebuild when unrelated properties are updated.
///
/// Typical usage is as follows: /// Typical usage is as follows:
/// ///
/// ```dart /// ```dart
@ -922,23 +990,182 @@ class MediaQuery extends InheritedWidget {
/// instead of returning null. /// instead of returning null.
static MediaQueryData? maybeOf(BuildContext context) { static MediaQueryData? maybeOf(BuildContext context) {
assert(context != null); assert(context != null);
return context.dependOnInheritedWidgetOfExactType<MediaQuery>()?.data; return _maybeOf(context);
} }
/// Returns textScaleFactor for the nearest MediaQuery ancestor or 1.0, if static MediaQueryData? _maybeOf(BuildContext context, [_MediaQueryAspect? aspect]) {
/// no such ancestor exists. return InheritedModel.inheritFrom<MediaQuery>(context, aspect: aspect)?.data;
static double textScaleFactorOf(BuildContext context) {
return MediaQuery.maybeOf(context)?.textScaleFactor ?? 1.0;
} }
/// Returns size for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.size] property of the ancestor [MediaQuery] changes.
static Size sizeOf(BuildContext context) => _of(context, _MediaQueryAspect.size).size;
/// Returns size for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.size] property of the ancestor [MediaQuery] changes.
static Size? maybeSizeOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.size)?.size;
/// Returns orientation for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.orientation] property of the ancestor [MediaQuery] changes.
static Orientation orientationOf(BuildContext context) => _of(context, _MediaQueryAspect.orientation).orientation;
/// Returns orientation for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.orientation] property of the ancestor [MediaQuery] changes.
static Orientation? maybeOrientationOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.orientation)?.orientation;
/// Returns devicePixelRatio for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.devicePixelRatio] property of the ancestor [MediaQuery] changes.
static double devicePixelRatioOf(BuildContext context) => _of(context, _MediaQueryAspect.devicePixelRatio).devicePixelRatio;
/// Returns devicePixelRatio for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.devicePixelRatio] property of the ancestor [MediaQuery] changes.
static double? maybeDevicePixelRatioOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.devicePixelRatio)?.devicePixelRatio;
/// Returns textScaleFactor for the nearest MediaQuery ancestor or
/// 1.0, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.textScaleFactor] property of the ancestor [MediaQuery] changes.
static double textScaleFactorOf(BuildContext context) => maybeTextScaleFactorOf(context) ?? 1.0;
/// Returns textScaleFactor for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.textScaleFactor] property of the ancestor [MediaQuery] changes.
static double? maybeTextScaleFactorOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.textScaleFactor)?.textScaleFactor;
/// Returns platformBrightness for the nearest MediaQuery ancestor or /// Returns platformBrightness for the nearest MediaQuery ancestor or
/// [Brightness.light], if no such ancestor exists. /// [Brightness.light], if no such ancestor exists.
/// ///
/// Use of this method will cause the given [context] to rebuild any time that /// Use of this method will cause the given [context] to rebuild any time that
/// any property of the ancestor [MediaQuery] changes. /// the [MediaQueryData.platformBrightness] property of the ancestor
static Brightness platformBrightnessOf(BuildContext context) { /// [MediaQuery] changes.
return MediaQuery.maybeOf(context)?.platformBrightness ?? Brightness.light; static Brightness platformBrightnessOf(BuildContext context) => maybePlatformBrightnessOf(context) ?? Brightness.light;
}
/// Returns platformBrightness for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.platformBrightness] property of the ancestor
/// [MediaQuery] changes.
static Brightness? maybePlatformBrightnessOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.platformBrightness)?.platformBrightness;
/// Returns padding for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.padding] property of the ancestor [MediaQuery] changes.
static EdgeInsets paddingOf(BuildContext context) => _of(context, _MediaQueryAspect.padding).padding;
/// Returns viewInsets for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.viewInsets] property of the ancestor [MediaQuery] changes.
static EdgeInsets? maybePaddingOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.padding)?.padding;
/// Returns viewInsets for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.viewInsets] property of the ancestor [MediaQuery] changes.
static EdgeInsets viewInsetsOf(BuildContext context) => _of(context, _MediaQueryAspect.viewInsets).viewInsets;
/// Returns viewInsets for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.viewInsets] property of the ancestor [MediaQuery] changes.
static EdgeInsets? maybeViewInsetsOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.viewInsets)?.viewInsets;
/// Returns systemGestureInsets for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.systemGestureInsets] property of the ancestor [MediaQuery] changes.
static EdgeInsets systemGestureInsetsOf(BuildContext context) => _of(context, _MediaQueryAspect.systemGestureInsets).systemGestureInsets;
/// Returns systemGestureInsets for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.systemGestureInsets] property of the ancestor [MediaQuery] changes.
static EdgeInsets? maybeSystemGestureInsetsOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.systemGestureInsets)?.systemGestureInsets;
/// Returns viewPadding for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.viewPadding] property of the ancestor [MediaQuery] changes.
static EdgeInsets viewPaddingOf(BuildContext context) => _of(context, _MediaQueryAspect.viewPadding).viewPadding;
/// Returns viewPadding for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.viewPadding] property of the ancestor [MediaQuery] changes.
static EdgeInsets? maybeViewPaddingOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.viewPadding)?.viewPadding;
/// Returns alwaysUse for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.devicePixelRatio] property of the ancestor [MediaQuery] changes.
static bool alwaysUse24HourFormatOf(BuildContext context) => _of(context, _MediaQueryAspect.alwaysUse24HourFormat).alwaysUse24HourFormat;
/// Returns alwaysUse24HourFormat for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.alwaysUse24HourFormat] property of the ancestor [MediaQuery] changes.
static bool? maybeAlwaysUse24HourFormatOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.alwaysUse24HourFormat)?.alwaysUse24HourFormat;
/// Returns accessibleNavigationOf for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.accessibleNavigation] property of the ancestor [MediaQuery] changes.
static bool accessibleNavigationOf(BuildContext context) => _of(context, _MediaQueryAspect.accessibleNavigation).accessibleNavigation;
/// Returns accessibleNavigation for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.accessibleNavigation] property of the ancestor [MediaQuery] changes.
static bool? maybeAccessibleNavigationOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.accessibleNavigation)?.accessibleNavigation;
/// Returns invertColorsOf for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.invertColors] property of the ancestor [MediaQuery] changes.
static bool invertColorsOf(BuildContext context) => _of(context, _MediaQueryAspect.invertColors).invertColors;
/// Returns invertColors for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.invertColors] property of the ancestor [MediaQuery] changes.
static bool? maybeInvertColorsOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.invertColors)?.invertColors;
/// Returns highContrast for the nearest MediaQuery ancestor or false, if no /// Returns highContrast for the nearest MediaQuery ancestor or false, if no
/// such ancestor exists. /// such ancestor exists.
@ -947,15 +1174,102 @@ class MediaQuery extends InheritedWidget {
/// ///
/// * [MediaQueryData.highContrast], which indicates the platform's /// * [MediaQueryData.highContrast], which indicates the platform's
/// desire to increase contrast. /// desire to increase contrast.
static bool highContrastOf(BuildContext context) { ///
return MediaQuery.maybeOf(context)?.highContrast ?? false; /// Use of this method will cause the given [context] to rebuild any time that
} /// the [MediaQueryData.highContrast] property of the ancestor [MediaQuery] changes.
static bool highContrastOf(BuildContext context) => maybeHighContrastOf(context) ?? false;
/// Returns highContrast for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.highContrast] property of the ancestor [MediaQuery] changes.
static bool? maybeHighContrastOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.highContrast)?.highContrast;
/// Returns disableAnimations for the nearest MediaQuery ancestor or
/// [Brightness.light], if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.disableAnimations] property of the ancestor
/// [MediaQuery] changes.
static bool disableAnimationsOf(BuildContext context) => _of(context, _MediaQueryAspect.disableAnimations).disableAnimations;
/// Returns disableAnimations for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.disableAnimations] property of the ancestor [MediaQuery] changes.
static bool? maybeDisableAnimationsOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.disableAnimations)?.disableAnimations;
/// Returns the boldText accessibility setting for the nearest MediaQuery /// Returns the boldText accessibility setting for the nearest MediaQuery
/// ancestor, or false if no such ancestor exists. /// ancestor or false, if no such ancestor exists.
static bool boldTextOverride(BuildContext context) { ///
return MediaQuery.maybeOf(context)?.boldText ?? false; /// Use of this method will cause the given [context] to rebuild any time that
} /// the [MediaQueryData.boldText] property of the ancestor [MediaQuery] changes.
static bool boldTextOf(BuildContext context) => maybeBoldTextOf(context) ?? false;
/// Returns the boldText accessibility setting for the nearest MediaQuery
/// ancestor or false, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.boldText] property of the ancestor [MediaQuery] changes.
///
/// Deprecated in favor of [boldTextOf].
@Deprecated(
'Migrate to boldTextOf. '
'This feature was deprecated after v3.5.0-9.0.pre.'
)
static bool boldTextOverride(BuildContext context) => boldTextOf(context);
/// Returns the boldText accessibility setting for the nearest MediaQuery
/// ancestor or null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.boldText] property of the ancestor [MediaQuery] changes.
static bool? maybeBoldTextOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.boldText)?.boldText;
/// Returns navigationMode for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.navigationMode] property of the ancestor [MediaQuery] changes.
static NavigationMode navigationModeOf(BuildContext context) => _of(context, _MediaQueryAspect.navigationMode).navigationMode;
/// Returns navigationMode for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.navigationMode] property of the ancestor [MediaQuery] changes.
static NavigationMode? maybeNavigationModeOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.navigationMode)?.navigationMode;
/// Returns gestureSettings for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.gestureSettings] property of the ancestor [MediaQuery] changes.
static DeviceGestureSettings gestureSettingsOf(BuildContext context) => _of(context, _MediaQueryAspect.gestureSettings).gestureSettings;
/// Returns gestureSettings for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.gestureSettings] property of the ancestor [MediaQuery] changes.
static DeviceGestureSettings? maybeGestureSettingsOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.gestureSettings)?.gestureSettings;
/// Returns displayFeatures for the nearest MediaQuery ancestor or
/// throws an exception, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.displayFeatures] property of the ancestor [MediaQuery] changes.
static List<ui.DisplayFeature> displayFeaturesOf(BuildContext context) => _of(context, _MediaQueryAspect.displayFeatures).displayFeatures;
/// Returns displayFeatures for the nearest MediaQuery ancestor or
/// null, if no such ancestor exists.
///
/// Use of this method will cause the given [context] to rebuild any time that
/// the [MediaQueryData.displayFeatures] property of the ancestor [MediaQuery] changes.
static List<ui.DisplayFeature>? maybeDisplayFeaturesOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.displayFeatures)?.displayFeatures;
@override @override
bool updateShouldNotify(MediaQuery oldWidget) => data != oldWidget.data; bool updateShouldNotify(MediaQuery oldWidget) => data != oldWidget.data;
@ -965,6 +1279,27 @@ class MediaQuery extends InheritedWidget {
super.debugFillProperties(properties); super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MediaQueryData>('data', data, showName: false)); properties.add(DiagnosticsProperty<MediaQueryData>('data', data, showName: false));
} }
@override
bool updateShouldNotifyDependent(MediaQuery oldWidget, Set<Object> dependencies) {
return (data.size != oldWidget.data.size && dependencies.contains(_MediaQueryAspect.size))
|| (data.orientation != oldWidget.data.orientation && dependencies.contains(_MediaQueryAspect.orientation))
|| (data.devicePixelRatio != oldWidget.data.devicePixelRatio && dependencies.contains(_MediaQueryAspect.devicePixelRatio))
|| (data.textScaleFactor != oldWidget.data.textScaleFactor && dependencies.contains(_MediaQueryAspect.textScaleFactor))
|| (data.platformBrightness != oldWidget.data.platformBrightness && dependencies.contains(_MediaQueryAspect.platformBrightness))
|| (data.viewInsets != oldWidget.data.viewInsets && dependencies.contains(_MediaQueryAspect.viewInsets))
|| (data.systemGestureInsets != oldWidget.data.systemGestureInsets && dependencies.contains(_MediaQueryAspect.systemGestureInsets))
|| (data.viewPadding != oldWidget.data.viewPadding && dependencies.contains(_MediaQueryAspect.viewPadding))
|| (data.alwaysUse24HourFormat != oldWidget.data.alwaysUse24HourFormat && dependencies.contains(_MediaQueryAspect.alwaysUse24HourFormat))
|| (data.accessibleNavigation != oldWidget.data.accessibleNavigation && dependencies.contains(_MediaQueryAspect.accessibleNavigation))
|| (data.invertColors != oldWidget.data.invertColors && dependencies.contains(_MediaQueryAspect.invertColors))
|| (data.highContrast != oldWidget.data.highContrast && dependencies.contains(_MediaQueryAspect.highContrast))
|| (data.disableAnimations != oldWidget.data.disableAnimations && dependencies.contains(_MediaQueryAspect.disableAnimations))
|| (data.boldText != oldWidget.data.boldText && dependencies.contains(_MediaQueryAspect.boldText))
|| (data.navigationMode != oldWidget.data.navigationMode && dependencies.contains(_MediaQueryAspect.navigationMode))
|| (data.gestureSettings != oldWidget.data.gestureSettings && dependencies.contains(_MediaQueryAspect.gestureSettings))
|| (data.displayFeatures != oldWidget.data.displayFeatures && dependencies.contains(_MediaQueryAspect.displayFeatures));
}
} }
/// Describes the navigation mode to be set by a [MediaQuery] widget. /// Describes the navigation mode to be set by a [MediaQuery] widget.
@ -972,7 +1307,7 @@ class MediaQuery extends InheritedWidget {
/// The different modes indicate the type of navigation to be used in a widget /// The different modes indicate the type of navigation to be used in a widget
/// subtree for those widgets sensitive to it. /// subtree for those widgets sensitive to it.
/// ///
/// Use `MediaQuery.of(context).navigationMode` to determine the navigation mode /// Use `MediaQuery.navigationModeOf(context)` to determine the navigation mode
/// in effect for the given context. Use a [MediaQuery] widget to set the /// in effect for the given context. Use a [MediaQuery] widget to set the
/// navigation mode for its descendant widgets. /// navigation mode for its descendant widgets.
enum NavigationMode { enum NavigationMode {

View File

@ -774,7 +774,7 @@ class _StretchingOverscrollIndicatorState extends State<StretchingOverscrollIndi
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size; final Size size = MediaQuery.sizeOf(context);
double mainAxisSize; double mainAxisSize;
return NotificationListener<ScrollNotification>( return NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification, onNotification: _handleScrollNotification,

View File

@ -1163,7 +1163,7 @@ class ReorderableDragStartListener extends StatelessWidget {
} }
void _startDragging(BuildContext context, PointerDownEvent event) { void _startDragging(BuildContext context, PointerDownEvent event) {
final DeviceGestureSettings? gestureSettings = MediaQuery.maybeOf(context)?.gestureSettings; final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context);
final SliverReorderableListState? list = SliverReorderableList.maybeOf(context); final SliverReorderableListState? list = SliverReorderableList.maybeOf(context);
list?.startItemDragReorder( list?.startItemDragReorder(
index: index, index: index,

View File

@ -93,11 +93,10 @@ class SafeArea extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final MediaQueryData data = MediaQuery.of(context); EdgeInsets padding = MediaQuery.paddingOf(context);
EdgeInsets padding = data.padding;
// Bottom padding has been consumed - i.e. by the keyboard // Bottom padding has been consumed - i.e. by the keyboard
if (maintainBottomViewPadding) { if (maintainBottomViewPadding) {
padding = padding.copyWith(bottom: data.viewPadding.bottom); padding = padding.copyWith(bottom: MediaQuery.viewPaddingOf(context).bottom);
} }
return Padding( return Padding(
@ -192,7 +191,7 @@ class SliverSafeArea extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMediaQuery(context));
final EdgeInsets padding = MediaQuery.of(context).padding; final EdgeInsets padding = MediaQuery.paddingOf(context);
return SliverPadding( return SliverPadding(
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: math.max(left ? padding.left : 0.0, minimum.left), left: math.max(left ? padding.left : 0.0, minimum.left),

View File

@ -461,7 +461,7 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R
late ScrollBehavior _configuration; late ScrollBehavior _configuration;
ScrollPhysics? _physics; ScrollPhysics? _physics;
ScrollController? _fallbackScrollController; ScrollController? _fallbackScrollController;
MediaQueryData? _mediaQueryData; DeviceGestureSettings? _mediaQueryGestureSettings;
ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!; ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!;
@ -516,7 +516,7 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R
@override @override
void didChangeDependencies() { void didChangeDependencies() {
_mediaQueryData = MediaQuery.maybeOf(context); _mediaQueryGestureSettings = MediaQuery.maybeGestureSettingsOf(context);
_updatePosition(); _updatePosition();
super.didChangeDependencies(); super.didChangeDependencies();
} }
@ -635,7 +635,7 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R
..maxFlingVelocity = _physics?.maxFlingVelocity ..maxFlingVelocity = _physics?.maxFlingVelocity
..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context) ..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context)
..dragStartBehavior = widget.dragStartBehavior ..dragStartBehavior = widget.dragStartBehavior
..gestureSettings = _mediaQueryData?.gestureSettings; ..gestureSettings = _mediaQueryGestureSettings;
}, },
), ),
}; };
@ -656,7 +656,7 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R
..maxFlingVelocity = _physics?.maxFlingVelocity ..maxFlingVelocity = _physics?.maxFlingVelocity
..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context) ..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context)
..dragStartBehavior = widget.dragStartBehavior ..dragStartBehavior = widget.dragStartBehavior
..gestureSettings = _mediaQueryData?.gestureSettings; ..gestureSettings = _mediaQueryGestureSettings;
}, },
), ),
}; };

View File

@ -1675,7 +1675,7 @@ class RawScrollbarState<T extends RawScrollbar> extends State<T> with TickerProv
..textDirection = Directionality.of(context) ..textDirection = Directionality.of(context)
..thickness = widget.thickness ?? _kScrollbarThickness ..thickness = widget.thickness ?? _kScrollbarThickness
..radius = widget.radius ..radius = widget.radius
..padding = widget.padding ?? MediaQuery.of(context).padding ..padding = widget.padding ?? MediaQuery.paddingOf(context)
..scrollbarOrientation = widget.scrollbarOrientation ..scrollbarOrientation = widget.scrollbarOrientation
..mainAxisMargin = widget.mainAxisMargin ..mainAxisMargin = widget.mainAxisMargin
..shape = widget.shape ..shape = widget.shape

View File

@ -350,7 +350,7 @@ class SelectableRegionState extends State<SelectableRegion> with TextSelectionDe
} }
// Hide the text selection toolbar on mobile when orientation changes. // Hide the text selection toolbar on mobile when orientation changes.
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
if (_lastOrientation == null) { if (_lastOrientation == null) {
_lastOrientation = orientation; _lastOrientation = orientation;
return; return;

View File

@ -141,7 +141,7 @@ class SnapshotWidget extends SingleChildRenderObjectWidget {
return _RenderSnapshotWidget( return _RenderSnapshotWidget(
controller: controller, controller: controller,
mode: mode, mode: mode,
devicePixelRatio: MediaQuery.of(context).devicePixelRatio, devicePixelRatio: MediaQuery.devicePixelRatioOf(context),
painter: painter, painter: painter,
autoresize: autoresize, autoresize: autoresize,
); );
@ -153,7 +153,7 @@ class SnapshotWidget extends SingleChildRenderObjectWidget {
(renderObject as _RenderSnapshotWidget) (renderObject as _RenderSnapshotWidget)
..controller = controller ..controller = controller
..mode = mode ..mode = mode
..devicePixelRatio = MediaQuery.of(context).devicePixelRatio ..devicePixelRatio = MediaQuery.devicePixelRatioOf(context)
..painter = painter ..painter = painter
..autoresize = autoresize; ..autoresize = autoresize;
} }

View File

@ -598,7 +598,7 @@ class Text extends StatelessWidget {
if (style == null || style!.inherit) { if (style == null || style!.inherit) {
effectiveTextStyle = defaultTextStyle.style.merge(style); effectiveTextStyle = defaultTextStyle.style.merge(style);
} }
if (MediaQuery.boldTextOverride(context)) { if (MediaQuery.boldTextOf(context)) {
effectiveTextStyle = effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold)); effectiveTextStyle = effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold));
} }
final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context); final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context);

View File

@ -362,7 +362,7 @@ void main() {
await tester.pumpWidget( await tester.pumpWidget(
createAppWithButtonThatLaunchesActionSheet( createAppWithButtonThatLaunchesActionSheet(
Builder(builder: (BuildContext context) { Builder(builder: (BuildContext context) {
screenHeight = MediaQuery.of(context).size.height; screenHeight = MediaQuery.sizeOf(context).height;
return MediaQuery( return MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0),
child: CupertinoActionSheet( child: CupertinoActionSheet(

View File

@ -588,7 +588,7 @@ void main() {
await tester.pumpWidget( await tester.pumpWidget(
createAppWithButtonThatLaunchesDialog( createAppWithButtonThatLaunchesDialog(
dialogBuilder: (BuildContext context) { dialogBuilder: (BuildContext context) {
dividerWidth = 1.0 / MediaQuery.of(context).devicePixelRatio; dividerWidth = 1.0 / MediaQuery.devicePixelRatioOf(context);
return CupertinoAlertDialog( return CupertinoAlertDialog(
title: const Text('The Title'), title: const Text('The Title'),
content: const Text('The message'), content: const Text('The message'),
@ -633,7 +633,7 @@ void main() {
await tester.pumpWidget( await tester.pumpWidget(
createAppWithButtonThatLaunchesDialog( createAppWithButtonThatLaunchesDialog(
dialogBuilder: (BuildContext context) { dialogBuilder: (BuildContext context) {
dividerThickness = 1.0 / MediaQuery.of(context).devicePixelRatio; dividerThickness = 1.0 / MediaQuery.devicePixelRatioOf(context);
return CupertinoAlertDialog( return CupertinoAlertDialog(
title: const Text('The Title'), title: const Text('The Title'),
content: const Text('The message'), content: const Text('The message'),
@ -841,7 +841,7 @@ void main() {
await tester.pumpWidget( await tester.pumpWidget(
createAppWithButtonThatLaunchesDialog( createAppWithButtonThatLaunchesDialog(
dialogBuilder: (BuildContext context) { dialogBuilder: (BuildContext context) {
dividerThickness = 1.0 / MediaQuery.of(context).devicePixelRatio; dividerThickness = 1.0 / MediaQuery.devicePixelRatioOf(context);
return CupertinoAlertDialog( return CupertinoAlertDialog(
title: const Text('The Title'), title: const Text('The Title'),
content: const Text('The message'), content: const Text('The message'),

View File

@ -117,14 +117,14 @@ void main() {
caretRect: reasonableTextField, caretRect: reasonableTextField,
// The tap position is far out of the right side of the app. // The tap position is far out of the right side of the app.
globalGesturePosition: globalGesturePosition:
Offset(MediaQuery.of(context).size.width + 100, 0), Offset(MediaQuery.sizeOf(context).width + 100, 0),
), ),
), ),
); );
// Should be less than the right edge, since we have padding. // Should be less than the right edge, since we have padding.
expect(getMagnifierPosition(tester).dx, expect(getMagnifierPosition(tester).dx,
lessThan(MediaQuery.of(context).size.width)); lessThan(MediaQuery.sizeOf(context).width));
}); });
testWidgets('should have some vertical drag', (WidgetTester tester) async { testWidgets('should have some vertical drag', (WidgetTester tester) async {
@ -150,7 +150,7 @@ void main() {
caretRect: reasonableTextField, caretRect: reasonableTextField,
// The tap position is dragBelow units below the text field. // The tap position is dragBelow units below the text field.
globalGesturePosition: Offset( globalGesturePosition: Offset(
MediaQuery.of(context).size.width / 2, MediaQuery.sizeOf(context).width / 2,
dragPositionBelowTextField), dragPositionBelowTextField),
), ),
), ),
@ -184,7 +184,7 @@ void main() {
caretRect: reasonableTextField, caretRect: reasonableTextField,
// The tap position is dragBelow units below the text field. // The tap position is dragBelow units below the text field.
globalGesturePosition: Offset( globalGesturePosition: Offset(
MediaQuery.of(context).size.width / 2, reasonableTextField.top), MediaQuery.sizeOf(context).width / 2, reasonableTextField.top),
), ),
); );
@ -223,7 +223,7 @@ void main() {
fieldBounds: reasonableTextField, fieldBounds: reasonableTextField,
caretRect: reasonableTextField, caretRect: reasonableTextField,
// The tap position is dragBelow units below the text field. // The tap position is dragBelow units below the text field.
globalGesturePosition: Offset(MediaQuery.of(context).size.width / 2, reasonableTextField.top), globalGesturePosition: Offset(MediaQuery.sizeOf(context).width / 2, reasonableTextField.top),
), ),
); );
@ -247,7 +247,7 @@ void main() {
currentLineBoundaries: reasonableTextField, currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField, fieldBounds: reasonableTextField,
caretRect: reasonableTextField, caretRect: reasonableTextField,
globalGesturePosition: Offset(MediaQuery.of(context).size.width / 2, globalGesturePosition: Offset(MediaQuery.sizeOf(context).width / 2,
reasonableTextField.top)); reasonableTextField.top));
await tester.pumpAndSettle(); await tester.pumpAndSettle();

View File

@ -501,7 +501,7 @@ void main() {
items: List<BottomNavigationBarItem>.generate(2, tabGenerator), items: List<BottomNavigationBarItem>.generate(2, tabGenerator),
), ),
tabBuilder: (BuildContext context, int index) { tabBuilder: (BuildContext context, int index) {
contentPadding = MediaQuery.of(context).padding; contentPadding = MediaQuery.paddingOf(context);
return const Placeholder(); return const Placeholder();
}, },
), ),

View File

@ -26,10 +26,10 @@ class _CustomCupertinoTextSelectionControls extends CupertinoTextSelectionContro
ValueNotifier<ClipboardStatus>? clipboardStatus, ValueNotifier<ClipboardStatus>? clipboardStatus,
Offset? lastSecondaryTapDownPosition, Offset? lastSecondaryTapDownPosition,
) { ) {
final MediaQueryData mediaQuery = MediaQuery.of(context); final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
final double anchorX = (selectionMidpoint.dx + globalEditableRegion.left).clamp( final double anchorX = (selectionMidpoint.dx + globalEditableRegion.left).clamp(
_kArrowScreenPadding + mediaQuery.padding.left, _kArrowScreenPadding + mediaQueryPadding.left,
mediaQuery.size.width - mediaQuery.padding.right - _kArrowScreenPadding, MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding,
); );
final Offset anchorAbove = Offset( final Offset anchorAbove = Offset(
anchorX, anchorX,

View File

@ -475,7 +475,7 @@ void main() {
double? textScaleFactor; double? textScaleFactor;
await tester.pumpWidget(MaterialApp( await tester.pumpWidget(MaterialApp(
home: Builder(builder:(BuildContext context) { home: Builder(builder:(BuildContext context) {
textScaleFactor = MediaQuery.of(context).textScaleFactor; textScaleFactor = MediaQuery.textScaleFactorOf(context);
return Container(); return Container();
}), }),
)); ));

View File

@ -438,7 +438,7 @@ void main() {
home: Scaffold( home: Scaffold(
body: Builder( body: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
width = MediaQuery.of(context).size.width; width = MediaQuery.sizeOf(context).width;
return CustomScrollView( return CustomScrollView(
slivers: <Widget>[ slivers: <Widget>[
SliverAppBar( SliverAppBar(

View File

@ -2443,7 +2443,7 @@ void main() {
value: 1, value: 1,
child: Builder( child: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
mediaQueryPadding = MediaQuery.of(context).padding; mediaQueryPadding = MediaQuery.paddingOf(context);
return Text('-1-' * 500); // A long long text string. return Text('-1-' * 500); // A long long text string.
}, },
), ),

View File

@ -925,7 +925,7 @@ void main() {
extendBody: extendBody, extendBody: extendBody,
body: Builder( body: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
mediaQueryBottom = MediaQuery.of(context).padding.bottom; mediaQueryBottom = MediaQuery.paddingOf(context).bottom;
return Container(key: bodyKey); return Container(key: bodyKey);
}, },
), ),
@ -998,7 +998,7 @@ void main() {
), ),
body: Builder( body: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
mediaQueryTop = MediaQuery.of(context).padding.top; mediaQueryTop = MediaQuery.paddingOf(context).top;
return Container(key: bodyKey); return Container(key: bodyKey);
}, },
), ),
@ -1957,7 +1957,7 @@ void main() {
MaterialApp( MaterialApp(
home: Builder( home: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
screenWidth = MediaQuery.of(context).size.width; screenWidth = MediaQuery.sizeOf(context).width;
return Scaffold( return Scaffold(
endDrawer: const Drawer( endDrawer: const Drawer(
child: Text('Drawer'), child: Text('Drawer'),

View File

@ -229,7 +229,7 @@ void main() {
home: Scaffold( home: Scaffold(
body: Builder( body: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
width = MediaQuery.of(context).size.width; width = MediaQuery.sizeOf(context).width;
return GestureDetector( return GestureDetector(
key: tapTarget, key: tapTarget,

View File

@ -502,7 +502,7 @@ void main() {
children: <Widget>[ children: <Widget>[
const Text('top', textDirection: TextDirection.ltr), const Text('top', textDirection: TextDirection.ltr),
Builder(builder: (BuildContext context) { Builder(builder: (BuildContext context) {
innerMediaQueryPadding = MediaQuery.of(context).padding; innerMediaQueryPadding = MediaQuery.paddingOf(context);
return Container(); return Container();
}), }),
], ],

View File

@ -5,7 +5,7 @@
import 'dart:ui' show Brightness, DisplayFeature, DisplayFeatureState, DisplayFeatureType, GestureSettings, ViewConfiguration; import 'dart:ui' show Brightness, DisplayFeature, DisplayFeatureState, DisplayFeatureType, GestureSettings, ViewConfiguration;
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
void main() { void main() {
@ -686,21 +686,21 @@ void main() {
expect(insideHighContrast, true); expect(insideHighContrast, true);
}); });
testWidgets('MediaQuery.boldTextOverride', (WidgetTester tester) async { testWidgets('MediaQuery.boldTextOf', (WidgetTester tester) async {
late bool outsideBoldTextOverride; late bool outsideBoldTextOverride;
late bool insideBoldTextOverride; late bool insideBoldTextOverride;
await tester.pumpWidget( await tester.pumpWidget(
Builder( Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
outsideBoldTextOverride = MediaQuery.boldTextOverride(context); outsideBoldTextOverride = MediaQuery.boldTextOf(context);
return MediaQuery( return MediaQuery(
data: const MediaQueryData( data: const MediaQueryData(
boldText: true, boldText: true,
), ),
child: Builder( child: Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
insideBoldTextOverride = MediaQuery.boldTextOverride(context); insideBoldTextOverride = MediaQuery.boldTextOf(context);
return Container(); return Container();
}, },
), ),
@ -937,4 +937,80 @@ void main() {
expect(MediaQueryData.fromWindow(tester.binding.window).gestureSettings.touchSlop, closeTo(33.33, 0.1)); // Repeating, of course expect(MediaQueryData.fromWindow(tester.binding.window).gestureSettings.touchSlop, closeTo(33.33, 0.1)); // Repeating, of course
tester.binding.window.viewConfigurationTestValue = null; tester.binding.window.viewConfigurationTestValue = null;
}); });
testWidgets('MediaQuery can be partially depended-on', (WidgetTester tester) async {
MediaQueryData data = const MediaQueryData(
size: Size(800, 600),
textScaleFactor: 1.1
);
int sizeBuildCount = 0;
int textScaleFactorBuildCount = 0;
final Widget showSize = Builder(
builder: (BuildContext context) {
sizeBuildCount++;
return Text('size: ${MediaQuery.sizeOf(context)}');
}
);
final Widget showTextScaleFactor = Builder(
builder: (BuildContext context) {
textScaleFactorBuildCount++;
return Text('textScaleFactor: ${MediaQuery.textScaleFactorOf(context).toStringAsFixed(1)}');
}
);
final Widget page = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MediaQuery(
data: data,
child: Center(
child: Column(
children: <Widget>[
showSize,
showTextScaleFactor,
ElevatedButton(
onPressed: () {
setState(() {
data = data.copyWith(size: Size(data.size.width + 100, data.size.height));
});
},
child: const Text('Increase width by 100')
),
ElevatedButton(
onPressed: () {
setState(() {
data = data.copyWith(textScaleFactor: data.textScaleFactor + 0.1);
});
},
child: const Text('Increase textScaleFactor by 0.1')
)
]
)
)
);
},
);
await tester.pumpWidget(MaterialApp(home: page));
expect(find.text('size: Size(800.0, 600.0)'), findsOneWidget);
expect(find.text('textScaleFactor: 1.1'), findsOneWidget);
expect(sizeBuildCount, 1);
expect(textScaleFactorBuildCount, 1);
await tester.tap(find.text('Increase width by 100'));
await tester.pumpAndSettle();
expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget);
expect(find.text('textScaleFactor: 1.1'), findsOneWidget);
expect(sizeBuildCount, 2);
expect(textScaleFactorBuildCount, 1);
await tester.tap(find.text('Increase textScaleFactor by 0.1'));
await tester.pumpAndSettle();
expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget);
expect(find.text('textScaleFactor: 1.2'), findsOneWidget);
expect(sizeBuildCount, 2);
expect(textScaleFactorBuildCount, 2);
});
} }

View File

@ -28,7 +28,7 @@ class TestOrientedBox extends SingleChildRenderObjectWidget {
const TestOrientedBox({ super.key, super.child }); const TestOrientedBox({ super.key, super.child });
Decoration _getDecoration(BuildContext context) { Decoration _getDecoration(BuildContext context) {
final Orientation orientation = MediaQuery.of(context).orientation; final Orientation orientation = MediaQuery.orientationOf(context);
switch (orientation) { switch (orientation) {
case Orientation.landscape: case Orientation.landscape:
return const BoxDecoration(color: Color(0xFF00FF00)); return const BoxDecoration(color: Color(0xFF00FF00));

View File

@ -235,4 +235,7 @@ void main() {
scrollBehavior.buildViewportChrome(context, child, axisDirection); scrollBehavior.buildViewportChrome(context, child, axisDirection);
final CupertinoScrollBehavior cupertinoScrollBehavior = CupertinoScrollBehavior(); final CupertinoScrollBehavior cupertinoScrollBehavior = CupertinoScrollBehavior();
cupertinoScrollBehavior.buildViewportChrome(context, child, axisDirection); cupertinoScrollBehavior.buildViewportChrome(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOverride(context);
} }

View File

@ -235,4 +235,7 @@ void main() {
scrollBehavior.buildOverscrollIndicator(context, child, axisDirection); scrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
final CupertinoScrollBehavior cupertinoScrollBehavior = CupertinoScrollBehavior(); final CupertinoScrollBehavior cupertinoScrollBehavior = CupertinoScrollBehavior();
cupertinoScrollBehavior.buildOverscrollIndicator(context, child, axisDirection); cupertinoScrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOf(context);
} }

View File

@ -307,4 +307,7 @@ void main() {
ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(showTrackOnHover: nowShowing); ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(showTrackOnHover: nowShowing);
scrollbarTheme.copyWith(showTrackOnHover: nowShowing); scrollbarTheme.copyWith(showTrackOnHover: nowShowing);
scrollbarTheme.showTrackOnHover; scrollbarTheme.showTrackOnHover;
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOverride(context);
} }

View File

@ -303,4 +303,7 @@ void main() {
ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(trackVisibility: nowShowing); ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(trackVisibility: nowShowing);
scrollbarTheme.copyWith(trackVisibility: nowShowing); scrollbarTheme.copyWith(trackVisibility: nowShowing);
scrollbarTheme.trackVisibility; scrollbarTheme.trackVisibility;
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOf(context);
} }

View File

@ -150,4 +150,7 @@ void main() {
// Changes made in https://github.com/flutter/flutter/pull/78588 // Changes made in https://github.com/flutter/flutter/pull/78588
final ScrollBehavior scrollBehavior = ScrollBehavior(); final ScrollBehavior scrollBehavior = ScrollBehavior();
scrollBehavior.buildViewportChrome(context, child, axisDirection); scrollBehavior.buildViewportChrome(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOverride(context);
} }

View File

@ -150,4 +150,7 @@ void main() {
// Changes made in https://github.com/flutter/flutter/pull/78588 // Changes made in https://github.com/flutter/flutter/pull/78588
final ScrollBehavior scrollBehavior = ScrollBehavior(); final ScrollBehavior scrollBehavior = ScrollBehavior();
scrollBehavior.buildOverscrollIndicator(context, child, axisDirection); scrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOf(context);
} }