media_query.dart 35.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math' as math;
6
import 'dart:ui' as ui;
7
import 'dart:ui' show Brightness;
8

9
import 'package:flutter/foundation.dart';
10

11 12 13
import 'basic.dart';
import 'framework.dart';

14 15 16 17
/// Whether in portrait or landscape.
enum Orientation {
  /// Taller than wide.
  portrait,
18

19 20 21
  /// Wider than tall.
  landscape
}
22

23 24 25 26 27 28 29 30
/// Information about a piece of media (e.g., a window).
///
/// For example, the [MediaQueryData.size] property contains the width and
/// height of the current window.
///
/// To obtain the current [MediaQueryData] for a given [BuildContext], use the
/// [MediaQuery.of] function. For example, to obtain the size of the current
/// window, use `MediaQuery.of(context).size`.
31 32 33 34
///
/// If no [MediaQuery] is in scope then the [MediaQuery.of] method will throw an
/// exception, unless the `nullOk` argument is set to true, in which case it
/// returns null.
35
///
36
/// ## Insets and Padding
37
///
38 39
/// ![A diagram of padding, viewInsets, and viewPadding in correlation with each
/// other](https://flutter.github.io/assets-for-api-docs/assets/widgets/media_query.png)
40
///
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/// This diagram illustrates how [padding] relates to [viewPadding] and
/// [viewInsets], shown here in its simplest configuration, as the difference
/// between the two. In cases when the viewInsets exceed the viewPadding, like
/// when a software keyboard is shown below, padding goes to zero rather than a
/// negative value. Therefore, padding is calculated by taking
/// `max(0.0, viewPadding - viewInsets)`.
///
/// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/widgets/window_padding.mp4}
///
/// In this diagram, the black areas represent system UI that the app cannot
/// draw over. The red area represents view padding that the application may not
/// be able to detect gestures in and may not want to draw in. The grey area
/// represents the system keyboard, which can cover over the bottom view padding
/// when visible.
///
/// MediaQueryData includes three [EdgeInsets] values:
/// [padding], [viewPadding], and [viewInsets]. These values reflect the
/// configuration of the device and are used and optionally consumed by widgets
/// that position content within these insets. The padding value defines areas
/// that might not be completely visible, like the display "notch" on the iPhone
/// X. The viewInsets value defines areas that aren't visible at all, typically
/// because they're obscured by the device's keyboard. Similar to viewInsets,
/// viewPadding does not differentiate padding in areas that may be obscured.
/// For example, by using the viewPadding property, padding would defer to the
/// iPhone "safe area" regardless of whether a keyboard is showing.
///
/// The viewInsets and viewPadding are independent values, they're
/// measured from the edges of the MediaQuery widget's bounds. Together they
/// inform the [padding] property. The bounds of the top level MediaQuery
/// created by [WidgetsApp] are the same as the window that contains the app.
///
/// Widgets whose layouts consume space defined by [viewInsets], [viewPadding],
/// or [padding] should enclose their children in secondary MediaQuery
74
/// widgets that reduce those properties by the same amount.
75
/// The [removePadding], [removeViewPadding], and [removeViewInsets] methods are
76
/// useful for this.
77
///
78 79
/// See also:
///
80 81 82
///  * [Scaffold], [SafeArea], [CupertinoTabScaffold], and
///    [CupertinoPageScaffold], all of which are informed by [padding],
///    [viewPadding], and [viewInsets].
83
@immutable
84
class MediaQueryData {
85 86 87
  /// Creates data for a media query with explicit values.
  ///
  /// Consider using [MediaQueryData.fromWindow] to create data based on a
88
  /// [Window].
89
  const MediaQueryData({
90 91 92
    this.size = Size.zero,
    this.devicePixelRatio = 1.0,
    this.textScaleFactor = 1.0,
93
    this.platformBrightness = Brightness.light,
94 95
    this.padding = EdgeInsets.zero,
    this.viewInsets = EdgeInsets.zero,
96
    this.systemGestureInsets = EdgeInsets.zero,
97
    this.viewPadding = EdgeInsets.zero,
98
    this.alwaysUse24HourFormat = false,
99 100
    this.accessibleNavigation = false,
    this.invertColors = false,
101
    this.highContrast = false,
102
    this.disableAnimations = false,
103
    this.boldText = false,
104
    this.navigationMode = NavigationMode.traditional,
105 106 107 108 109 110 111 112 113 114 115 116 117
  }) : assert(size != null),
       assert(devicePixelRatio != null),
       assert(textScaleFactor != null),
       assert(platformBrightness != null),
       assert(padding != null),
       assert(viewInsets != null),
       assert(systemGestureInsets != null),
       assert(viewPadding != null),
       assert(alwaysUse24HourFormat != null),
       assert(accessibleNavigation != null),
       assert(invertColors != null),
       assert(highContrast != null),
       assert(disableAnimations != null),
118 119
       assert(boldText != null),
       assert(navigationMode != null);
120

121
  /// Creates data for a media query based on the given window.
122 123 124 125
  ///
  /// If you use this, you should ensure that you also register for
  /// notifications so that you can update your [MediaQueryData] when the
  /// window's metrics change. For example, see
126
  /// [WidgetsBindingObserver.didChangeMetrics] or [Window.onMetricsChanged].
127
  MediaQueryData.fromWindow(ui.Window window)
128
    : size = window.physicalSize / window.devicePixelRatio,
129
      devicePixelRatio = window.devicePixelRatio,
130
      textScaleFactor = window.textScaleFactor,
131
      platformBrightness = window.platformBrightness,
132
      padding = EdgeInsets.fromWindowPadding(window.padding, window.devicePixelRatio),
133
      viewPadding = EdgeInsets.fromWindowPadding(window.viewPadding, window.devicePixelRatio),
134
      viewInsets = EdgeInsets.fromWindowPadding(window.viewInsets, window.devicePixelRatio),
135
      systemGestureInsets = EdgeInsets.fromWindowPadding(window.systemGestureInsets, window.devicePixelRatio),
136
      accessibleNavigation = window.accessibilityFeatures.accessibleNavigation,
137
      invertColors = window.accessibilityFeatures.invertColors,
138
      disableAnimations = window.accessibilityFeatures.disableAnimations,
139
      boldText = window.accessibilityFeatures.boldText,
140
      highContrast = window.accessibilityFeatures.highContrast,
141 142
      alwaysUse24HourFormat = window.alwaysUse24HourFormat,
      navigationMode = NavigationMode.traditional;
143

144
  /// The size of the media in logical pixels (e.g, the size of the screen).
145 146 147 148 149
  ///
  /// Logical pixels are roughly the same visual size across devices. Physical
  /// pixels are the size of the actual hardware pixels on the device. The
  /// number of physical pixels per logical pixel is described by the
  /// [devicePixelRatio].
150 151
  final Size size;

152 153 154 155 156
  /// The number of device pixels for each logical pixel. This number might not
  /// be a power of two. Indeed, it might not even be an integer. For example,
  /// the Nexus 6 has a device pixel ratio of 3.5.
  final double devicePixelRatio;

157 158 159 160
  /// The number of font pixels for each logical pixel.
  ///
  /// For example, if the text scale factor is 1.5, text will be 50% larger than
  /// the specified font size.
161 162 163 164 165
  ///
  /// See also:
  ///
  ///  * [MediaQuery.textScaleFactorOf], a convenience method which returns the
  ///    textScaleFactor defined for a [BuildContext].
166 167
  final double textScaleFactor;

168 169 170 171 172 173 174 175 176
  /// The current brightness mode of the host platform.
  ///
  /// For example, starting in Android Pie, battery saver mode asks all apps to
  /// render in a "dark mode".
  ///
  /// Not all platforms necessarily support a concept of brightness mode. Those
  /// platforms will report [Brightness.light] in this property.
  final Brightness platformBrightness;

177 178 179 180 181 182
  /// The parts of the display that are completely obscured by system UI,
  /// typically by the device's keyboard.
  ///
  /// When a mobile device's keyboard is visible `viewInsets.bottom`
  /// corresponds to the top of the keyboard.
  ///
183 184 185 186 187
  /// This value is independent of the [padding] and [viewPadding]. viewPadding
  /// is measured from the edges of the [MediaQuery] widget's bounds. Padding is
  /// calculated based on the viewPadding and viewInsets. The bounds of the top
  /// level MediaQuery created by [WidgetsApp] are the same as the window
  /// (often the mobile device screen) that contains the app.
188 189 190
  ///
  /// See also:
  ///
191 192
  ///  * [ui.window], which provides some additional detail about this property
  ///    and how it relates to [padding] and [viewPadding].
193 194
  final EdgeInsets viewInsets;

195 196
  /// The parts of the display that are partially obscured by system UI,
  /// typically by the hardware display "notches" or the system status bar.
197 198 199 200
  ///
  /// If you consumed this padding (e.g. by building a widget that envelops or
  /// accounts for this padding in its layout in such a way that children are
  /// no longer exposed to this padding), you should remove this padding
201
  /// for subsequent descendants in the widget tree by inserting a new
202 203
  /// [MediaQuery] widget using the [MediaQuery.removePadding] factory.
  ///
204
  /// Padding is derived from the values of [viewInsets] and [viewPadding].
205
  ///
206 207
  /// See also:
  ///
208 209
  ///  * [ui.window], which provides some additional detail about this
  ///    property and how it relates to [viewInsets] and [viewPadding].
210 211
  ///  * [SafeArea], a widget that consumes this padding with a [Padding] widget
  ///    and automatically removes it from the [MediaQuery] for its child.
212
  final EdgeInsets padding;
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  /// The parts of the display that are partially obscured by system UI,
  /// typically by the hardware display "notches" or the system status bar.
  ///
  /// This value remains the same regardless of whether the system is reporting
  /// other obstructions in the same physical area of the screen. For example, a
  /// software keyboard on the bottom of the screen that may cover and consume
  /// the same area that requires bottom padding will not affect this value.
  ///
  /// This value is independent of the [padding] and [viewInsets]: their values
  /// are measured from the edges of the [MediaQuery] widget's bounds. The
  /// bounds of the top level MediaQuery created by [WidgetsApp] are the
  /// same as the window that contains the app. On mobile devices, this will
  /// typically be the full screen.
  ///
  /// See also:
  ///
230 231
  ///  * [ui.window], which provides some additional detail about this
  ///    property and how it relates to [padding] and [viewInsets].
232 233
  final EdgeInsets viewPadding;

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
  /// The areas along the edges of the display where the system consumes
  /// certain input events and blocks delivery of those events to the app.
  ///
  /// Starting with Android Q, simple swipe gestures that start within the
  /// [systemGestureInsets] areas are used by the system for page navigation
  /// and may not be delivered to the app. Taps and swipe gestures that begin
  /// with a long-press are delivered to the app, but simple press-drag-release
  /// swipe gestures which begin within the area defined by [systemGestureInsets]
  /// may not be.
  ///
  /// Apps should avoid locating gesture detectors within the system gesture
  /// insets area. Apps should feel free to put visual elements within
  /// this area.
  ///
  /// This property is currently only expected to be set to a non-default value
  /// on Android starting with version Q.
  ///
251
  /// {@tool dartpad --template=stateful_widget_material}
252 253
  ///
  /// For apps that might be deployed on Android Q devices with full gesture
254
  /// navigation enabled, use [systemGestureInsets] with [Padding]
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  /// to avoid having the left and right edges of the [Slider] from appearing
  /// within the area reserved for system gesture navigation.
  ///
  /// By default, [Slider]s expand to fill the available width. So, we pad the
  /// left and right sides.
  ///
  /// ```dart
  /// double _currentValue = 0.2;
  ///
  /// @override
  /// Widget build(BuildContext context) {
  ///   EdgeInsets systemGestureInsets = MediaQuery.of(context).systemGestureInsets;
  ///   return Scaffold(
  ///     appBar: AppBar(title: Text('Pad Slider to avoid systemGestureInsets')),
  ///     body: Padding(
  ///       padding: EdgeInsets.only( // only left and right padding are needed here
  ///         left: systemGestureInsets.left,
  ///         right: systemGestureInsets.right,
  ///       ),
  ///       child: Slider(
  ///         value: _currentValue.toDouble(),
  ///         onChanged: (double newValue) {
  ///           setState(() {
  ///             _currentValue = newValue;
  ///           });
  ///         },
  ///       ),
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  final EdgeInsets systemGestureInsets;

289 290 291 292 293 294 295 296 297 298 299 300 301
  /// Whether to use 24-hour format when formatting time.
  ///
  /// The behavior of this flag is different across platforms:
  ///
  /// - On Android this flag is reported directly from the user settings called
  ///   "Use 24-hour format". It applies to any locale used by the application,
  ///   whether it is the system-wide locale, or the custom locale set by the
  ///   application.
  /// - On iOS this flag is set to true when the user setting called "24-Hour
  ///   Time" is set or the system-wide locale's default uses 24-hour
  ///   formatting.
  final bool alwaysUse24HourFormat;

302 303 304 305 306 307 308 309
  /// Whether the user is using an accessibility service like TalkBack or
  /// VoiceOver to interact with the application.
  ///
  /// When this setting is true, features such as timeouts should be disabled or
  /// have minimum durations increased.
  ///
  /// See also:
  ///
310
  ///  * [Window.accessibilityFeatures], where the setting originates.
311 312 313 314 315 316 317 318
  final bool accessibleNavigation;

  /// Whether the device is inverting the colors of the platform.
  ///
  /// This flag is currently only updated on iOS devices.
  ///
  /// See also:
  ///
319
  ///  * [Window.accessibilityFeatures], where the setting originates.
320 321
  final bool invertColors;

322 323 324 325 326 327 328
  /// Whether the user requested a high contrast between foreground and background
  /// content on iOS, via Settings -> Accessibility -> Increase Contrast.
  ///
  /// This flag is currently only updated on iOS devices that are running iOS 13
  /// or above.
  final bool highContrast;

329 330 331
  /// Whether the platform is requesting that animations be disabled or reduced
  /// as much as possible.
  ///
332 333
  /// See also:
  ///
334
  ///  * [Window.accessibilityFeatures], where the setting originates.
335 336
  final bool disableAnimations;

337 338 339 340 341
  /// Whether the platform is requesting that text be drawn with a bold font
  /// weight.
  ///
  /// See also:
  ///
342
  ///  * [Window.accessibilityFeatures], where the setting originates.
343 344
  final bool boldText;

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
  /// Describes the navigation mode requested by the platform.
  ///
  /// Some user interfaces are better navigated using a directional pad (DPAD)
  /// or arrow keys, and for those interfaces, some widgets need to handle these
  /// directional events differently. In order to know when to do that, these
  /// widgets will look for the navigation mode in effect for their context.
  ///
  /// For instance, in a television interface, [NavigationMode.directional]
  /// should be set, so that directional navigation is used to navigate away
  /// from a text field using the DPAD. In contrast, on a regular desktop
  /// application with the `navigationMode` set to [NavigationMode.traditional],
  /// the arrow keys are used to move the cursor instead of navigating away.
  ///
  /// The [NavigationMode] values indicate the type of navigation to be used in
  /// a widget subtree for those widgets sensitive to it.
  final NavigationMode navigationMode;

362 363
  /// The orientation of the media (e.g., whether the device is in landscape or
  /// portrait mode).
364 365 366 367
  Orientation get orientation {
    return size.width > size.height ? Orientation.landscape : Orientation.portrait;
  }

368 369
  /// Creates a copy of this media query data but with the given fields replaced
  /// with the new values.
370
  MediaQueryData copyWith({
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    Size? size,
    double? devicePixelRatio,
    double? textScaleFactor,
    Brightness? platformBrightness,
    EdgeInsets? padding,
    EdgeInsets? viewPadding,
    EdgeInsets? viewInsets,
    EdgeInsets? systemGestureInsets,
    bool? alwaysUse24HourFormat,
    bool? highContrast,
    bool? disableAnimations,
    bool? invertColors,
    bool? accessibleNavigation,
    bool? boldText,
    NavigationMode? navigationMode,
386
  }) {
387
    return MediaQueryData(
388 389 390
      size: size ?? this.size,
      devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
      textScaleFactor: textScaleFactor ?? this.textScaleFactor,
391
      platformBrightness: platformBrightness ?? this.platformBrightness,
392
      padding: padding ?? this.padding,
393
      viewPadding: viewPadding ?? this.viewPadding,
394
      viewInsets: viewInsets ?? this.viewInsets,
395
      systemGestureInsets: systemGestureInsets ?? this.systemGestureInsets,
396
      alwaysUse24HourFormat: alwaysUse24HourFormat ?? this.alwaysUse24HourFormat,
397
      invertColors: invertColors ?? this.invertColors,
398
      highContrast: highContrast ?? this.highContrast,
399 400
      disableAnimations: disableAnimations ?? this.disableAnimations,
      accessibleNavigation: accessibleNavigation ?? this.accessibleNavigation,
401
      boldText: boldText ?? this.boldText,
402
      navigationMode: navigationMode ?? this.navigationMode,
403 404 405
    );
  }

406
  /// Creates a copy of this media query data but with the given [padding]s
Ian Hickson's avatar
Ian Hickson committed
407 408 409 410 411 412 413 414
  /// replaced with zero.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then this
  /// [MediaQueryData] is returned unmodified.
  ///
  /// See also:
  ///
415
  ///  * [MediaQuery.removePadding], which uses this method to remove [padding]
Ian Hickson's avatar
Ian Hickson committed
416 417 418
  ///    from the ambient [MediaQuery].
  ///  * [SafeArea], which both removes the padding from the [MediaQuery] and
  ///    adds a [Padding] widget.
419
  ///  * [removeViewInsets], the same thing but for [viewInsets].
420
  ///  * [removeViewPadding], the same thing but for [viewPadding].
Ian Hickson's avatar
Ian Hickson committed
421
  MediaQueryData removePadding({
422 423 424 425
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
Ian Hickson's avatar
Ian Hickson committed
426 427 428
  }) {
    if (!(removeLeft || removeTop || removeRight || removeBottom))
      return this;
429
    return MediaQueryData(
Ian Hickson's avatar
Ian Hickson committed
430 431 432
      size: size,
      devicePixelRatio: devicePixelRatio,
      textScaleFactor: textScaleFactor,
433
      platformBrightness: platformBrightness,
Ian Hickson's avatar
Ian Hickson committed
434 435 436 437 438 439
      padding: padding.copyWith(
        left: removeLeft ? 0.0 : null,
        top: removeTop ? 0.0 : null,
        right: removeRight ? 0.0 : null,
        bottom: removeBottom ? 0.0 : null,
      ),
440
      viewPadding: viewPadding.copyWith(
441 442 443 444
        left: removeLeft ? math.max(0.0, viewPadding.left - padding.left) : null,
        top: removeTop ? math.max(0.0, viewPadding.top - padding.top) : null,
        right: removeRight ? math.max(0.0, viewPadding.right - padding.right) : null,
        bottom: removeBottom ? math.max(0.0, viewPadding.bottom - padding.bottom) : null,
445
      ),
446
      viewInsets: viewInsets,
447
      alwaysUse24HourFormat: alwaysUse24HourFormat,
448
      highContrast: highContrast,
449 450 451
      disableAnimations: disableAnimations,
      invertColors: invertColors,
      accessibleNavigation: accessibleNavigation,
452
      boldText: boldText,
Ian Hickson's avatar
Ian Hickson committed
453 454 455
    );
  }

456 457 458 459 460 461 462 463 464
  /// Creates a copy of this media query data but with the given [viewInsets]
  /// replaced with zero.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then this
  /// [MediaQueryData] is returned unmodified.
  ///
  /// See also:
  ///
465 466
  ///  * [MediaQuery.removeViewInsets], which uses this method to remove
  ///    [viewInsets] from the ambient [MediaQuery].
467
  ///  * [removePadding], the same thing but for [padding].
468
  ///  * [removeViewPadding], the same thing but for [viewPadding].
469
  MediaQueryData removeViewInsets({
470 471 472 473
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
474 475 476
  }) {
    if (!(removeLeft || removeTop || removeRight || removeBottom))
      return this;
477
    return MediaQueryData(
478 479 480
      size: size,
      devicePixelRatio: devicePixelRatio,
      textScaleFactor: textScaleFactor,
481
      platformBrightness: platformBrightness,
482
      padding: padding,
483
      viewPadding: viewPadding.copyWith(
484 485 486 487
        left: removeLeft ? math.max(0.0, viewPadding.left - viewInsets.left) : null,
        top: removeTop ? math.max(0.0, viewPadding.top - viewInsets.top) : null,
        right: removeRight ? math.max(0.0, viewPadding.right - viewInsets.right) : null,
        bottom: removeBottom ? math.max(0.0, viewPadding.bottom - viewInsets.bottom) : null,
488
      ),
489 490 491 492 493 494 495
      viewInsets: viewInsets.copyWith(
        left: removeLeft ? 0.0 : null,
        top: removeTop ? 0.0 : null,
        right: removeRight ? 0.0 : null,
        bottom: removeBottom ? 0.0 : null,
      ),
      alwaysUse24HourFormat: alwaysUse24HourFormat,
496
      highContrast: highContrast,
497 498 499
      disableAnimations: disableAnimations,
      invertColors: invertColors,
      accessibleNavigation: accessibleNavigation,
500
      boldText: boldText,
501 502 503
    );
  }

504 505 506 507 508 509 510 511 512
  /// Creates a copy of this media query data but with the given [viewPadding]
  /// replaced with zero.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then this
  /// [MediaQueryData] is returned unmodified.
  ///
  /// See also:
  ///
513 514
  ///  * [MediaQuery.removeViewPadding], which uses this method to remove
  ///    [viewPadding] from the ambient [MediaQuery].
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  ///  * [removePadding], the same thing but for [padding].
  ///  * [removeViewInsets], the same thing but for [viewInsets].
  MediaQueryData removeViewPadding({
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
  }) {
    if (!(removeLeft || removeTop || removeRight || removeBottom))
      return this;
    return MediaQueryData(
      size: size,
      devicePixelRatio: devicePixelRatio,
      textScaleFactor: textScaleFactor,
      platformBrightness: platformBrightness,
      padding: padding.copyWith(
        left: removeLeft ? 0.0 : null,
        top: removeTop ? 0.0 : null,
        right: removeRight ? 0.0 : null,
        bottom: removeBottom ? 0.0 : null,
      ),
      viewInsets: viewInsets,
      viewPadding: viewPadding.copyWith(
        left: removeLeft ? 0.0 : null,
        top: removeTop ? 0.0 : null,
        right: removeRight ? 0.0 : null,
        bottom: removeBottom ? 0.0 : null,
      ),
      alwaysUse24HourFormat: alwaysUse24HourFormat,
544
      highContrast: highContrast,
545 546 547 548 549 550 551
      disableAnimations: disableAnimations,
      invertColors: invertColors,
      accessibleNavigation: accessibleNavigation,
      boldText: boldText,
    );
  }

552
  @override
553
  bool operator ==(Object other) {
554 555
    if (other.runtimeType != runtimeType)
      return false;
556 557 558 559 560 561 562 563 564 565 566 567 568
    return other is MediaQueryData
        && other.size == size
        && other.devicePixelRatio == devicePixelRatio
        && other.textScaleFactor == textScaleFactor
        && other.platformBrightness == platformBrightness
        && other.padding == padding
        && other.viewPadding == viewPadding
        && other.viewInsets == viewInsets
        && other.alwaysUse24HourFormat == alwaysUse24HourFormat
        && other.highContrast == highContrast
        && other.disableAnimations == disableAnimations
        && other.invertColors == invertColors
        && other.accessibleNavigation == accessibleNavigation
569 570
        && other.boldText == boldText
        && other.navigationMode == navigationMode;
571 572
  }

573
  @override
574 575 576 577 578
  int get hashCode {
    return hashValues(
      size,
      devicePixelRatio,
      textScaleFactor,
579
      platformBrightness,
580
      padding,
581
      viewPadding,
582 583
      viewInsets,
      alwaysUse24HourFormat,
584
      highContrast,
585 586 587
      disableAnimations,
      invertColors,
      accessibleNavigation,
588
      boldText,
589
      navigationMode,
590 591
    );
  }
592

593
  @override
594
  String toString() {
595 596 597 598 599 600 601 602 603 604 605 606 607 608
    final List<String> properties = <String>[
      'size: $size',
      'devicePixelRatio: ${devicePixelRatio.toStringAsFixed(1)}',
      'textScaleFactor: ${textScaleFactor.toStringAsFixed(1)}',
      'platformBrightness: $platformBrightness',
      'padding: $padding',
      'viewPadding: $viewPadding',
      'viewInsets: $viewInsets',
      'alwaysUse24HourFormat: $alwaysUse24HourFormat',
      'accessibleNavigation: $accessibleNavigation',
      'highContrast: $highContrast',
      'disableAnimations: $disableAnimations',
      'invertColors: $invertColors',
      'boldText: $boldText',
609
      'navigationMode: ${describeEnum(navigationMode)}',
610 611
    ];
    return '${objectRuntimeType(this, 'MediaQueryData')}(${properties.join(', ')})';
612
  }
613 614
}

615
/// Establishes a subtree in which media queries resolve to the given data.
616 617 618 619 620 621 622 623 624
///
/// For example, to learn the size of the current media (e.g., the window
/// containing your app), you can read the [MediaQueryData.size] property from
/// the [MediaQueryData] returned by [MediaQuery.of]:
/// `MediaQuery.of(context).size`.
///
/// Querying the current media using [MediaQuery.of] will cause your widget to
/// rebuild automatically whenever the [MediaQueryData] changes (e.g., if the
/// user rotates their device).
625 626 627 628 629
///
/// If no [MediaQuery] is in scope then the [MediaQuery.of] method will throw an
/// exception, unless the `nullOk` argument is set to true, in which case it
/// returns null.
///
630 631
/// {@youtube 560 315 https://www.youtube.com/watch?v=A3WrA4zAaPw}
///
632 633 634 635 636
/// See also:
///
///  * [WidgetsApp] and [MaterialApp], which introduce a [MediaQuery] and keep
///    it up to date with the current screen metrics as they change.
///  * [MediaQueryData], the data structure that represents the metrics.
637
class MediaQuery extends InheritedWidget {
638 639 640
  /// Creates a widget that provides [MediaQueryData] to its descendants.
  ///
  /// The [data] and [child] arguments must not be null.
641
  const MediaQuery({
642 643 644
    Key? key,
    required this.data,
    required Widget child,
645 646 647
  }) : assert(child != null),
       assert(data != null),
       super(key: key, child: child);
648

649 650
  /// Creates a new [MediaQuery] that inherits from the ambient [MediaQuery]
  /// from the given context, but removes the specified padding.
Ian Hickson's avatar
Ian Hickson committed
651
  ///
652
  /// This should be inserted into the widget tree when the [MediaQuery] padding
653
  /// is consumed by a widget in such a way that the padding is no longer
654
  /// exposed to the widget's descendants or siblings.
655
  ///
Ian Hickson's avatar
Ian Hickson committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669
  /// The [context] argument is required, must not be null, and must have a
  /// [MediaQuery] in scope.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then the returned
  /// [MediaQuery] reuses the ambient [MediaQueryData] unmodified, which is not
  /// particularly useful.
  ///
  /// The [child] argument is required and must not be null.
  ///
  /// See also:
  ///
  ///  * [SafeArea], which both removes the padding from the [MediaQuery] and
  ///    adds a [Padding] widget.
670 671 672 673 674
  ///  * [MediaQueryData.padding], the affected property of the
  ///    [MediaQueryData].
  ///  * [removeViewInsets], the same thing but for [MediaQueryData.viewInsets].
  ///  * [removeViewPadding], the same thing but for
  ///    [MediaQueryData.viewPadding].
Ian Hickson's avatar
Ian Hickson committed
675
  factory MediaQuery.removePadding({
676 677
    Key? key,
    required BuildContext context,
678 679 680 681
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
682
    required Widget child,
Ian Hickson's avatar
Ian Hickson committed
683
  }) {
684
    return MediaQuery(
Ian Hickson's avatar
Ian Hickson committed
685
      key: key,
686
      data: MediaQuery.of(context)!.removePadding(
Ian Hickson's avatar
Ian Hickson committed
687 688 689 690 691
        removeLeft: removeLeft,
        removeTop: removeTop,
        removeRight: removeRight,
        removeBottom: removeBottom,
      ),
692 693 694 695
      child: child,
    );
  }

696 697
  /// Creates a new [MediaQuery] that inherits from the ambient [MediaQuery]
  /// from the given context, but removes the specified view insets.
698 699 700
  ///
  /// This should be inserted into the widget tree when the [MediaQuery] view
  /// insets are consumed by a widget in such a way that the view insets are no
701
  /// longer exposed to the widget's descendants or siblings.
702 703 704 705 706 707 708 709 710 711 712 713 714
  ///
  /// The [context] argument is required, must not be null, and must have a
  /// [MediaQuery] in scope.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then the returned
  /// [MediaQuery] reuses the ambient [MediaQueryData] unmodified, which is not
  /// particularly useful.
  ///
  /// The [child] argument is required and must not be null.
  ///
  /// See also:
  ///
715 716 717 718 719
  ///  * [MediaQueryData.viewInsets], the affected property of the
  ///    [MediaQueryData].
  ///  * [removePadding], the same thing but for [MediaQueryData.padding].
  ///  * [removeViewPadding], the same thing but for
  ///    [MediaQueryData.viewPadding].
720
  factory MediaQuery.removeViewInsets({
721 722
    Key? key,
    required BuildContext context,
723 724 725 726
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
727
    required Widget child,
728
  }) {
729
    return MediaQuery(
730
      key: key,
731
      data: MediaQuery.of(context)!.removeViewInsets(
732 733
        removeLeft: removeLeft,
        removeTop: removeTop,
734 735 736 737 738 739 740
        removeRight: removeRight,
        removeBottom: removeBottom,
      ),
      child: child,
    );
  }

741 742
  /// Creates a new [MediaQuery] that inherits from the ambient [MediaQuery]
  /// from the given context, but removes the specified view padding.
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  ///
  /// This should be inserted into the widget tree when the [MediaQuery] view
  /// padding is consumed by a widget in such a way that the view padding is no
  /// longer exposed to the widget's descendants or siblings.
  ///
  /// The [context] argument is required, must not be null, and must have a
  /// [MediaQuery] in scope.
  ///
  /// The `removeLeft`, `removeTop`, `removeRight`, and `removeBottom` arguments
  /// must not be null. If all four are false (the default) then the returned
  /// [MediaQuery] reuses the ambient [MediaQueryData] unmodified, which is not
  /// particularly useful.
  ///
  /// The [child] argument is required and must not be null.
  ///
  /// See also:
  ///
  ///  * [MediaQueryData.viewPadding], the affected property of the
761
  ///    [MediaQueryData].
762 763
  ///  * [removePadding], the same thing but for [MediaQueryData.padding].
  ///  * [removeViewInsets], the same thing but for [MediaQueryData.viewInsets].
764
  factory MediaQuery.removeViewPadding({
765 766
    Key? key,
    required BuildContext context,
767 768 769 770
    bool removeLeft = false,
    bool removeTop = false,
    bool removeRight = false,
    bool removeBottom = false,
771
    required Widget child,
772 773 774
  }) {
    return MediaQuery(
      key: key,
775
      data: MediaQuery.of(context)!.removeViewPadding(
776 777
        removeLeft: removeLeft,
        removeTop: removeTop,
778 779 780
        removeRight: removeRight,
        removeBottom: removeBottom,
      ),
Ian Hickson's avatar
Ian Hickson committed
781 782 783 784
      child: child,
    );
  }

785 786 787 788
  /// Contains information about the current media.
  ///
  /// For example, the [MediaQueryData.size] property contains the width and
  /// height of the current window.
789 790
  final MediaQueryData data;

791 792
  /// The data from the closest instance of this class that encloses the given
  /// context.
793 794
  ///
  /// You can use this function to query the size an orientation of the screen.
795 796
  /// When that information changes, your widget will be scheduled to be
  /// rebuilt, keeping your widget up-to-date.
797 798 799 800 801 802
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// MediaQueryData media = MediaQuery.of(context);
  /// ```
803 804 805 806 807 808
  ///
  /// If there is no [MediaQuery] in scope, then this will throw an exception.
  /// To return null if there is no [MediaQuery], then pass `nullOk: true`.
  ///
  /// If you use this from a widget (e.g. in its build function), consider
  /// calling [debugCheckHasMediaQuery].
809
  static MediaQueryData? of(BuildContext context, { bool nullOk = false }) {
Ian Hickson's avatar
Ian Hickson committed
810 811
    assert(context != null);
    assert(nullOk != null);
812
    final MediaQuery? query = context.dependOnInheritedWidgetOfExactType<MediaQuery>();
813 814 815 816
    if (query != null)
      return query.data;
    if (nullOk)
      return null;
817 818 819 820 821 822 823 824 825 826
    throw FlutterError.fromParts(<DiagnosticsNode>[
      ErrorSummary('MediaQuery.of() called with a context that does not contain a MediaQuery.'),
      ErrorDescription(
        'No MediaQuery ancestor could be found starting from the context that was passed '
        'to MediaQuery.of(). This can happen because you do not have a WidgetsApp or '
        'MaterialApp widget (those widgets introduce a MediaQuery), or it can happen '
        'if the context you use comes from a widget above those widgets.'
      ),
      context.describeElement('The context used was')
    ]);
827 828
  }

829 830 831 832 833 834
  /// Returns textScaleFactor for the nearest MediaQuery ancestor or 1.0, if
  /// no such ancestor exists.
  static double textScaleFactorOf(BuildContext context) {
    return MediaQuery.of(context, nullOk: true)?.textScaleFactor ?? 1.0;
  }

835 836 837 838 839 840 841 842 843
  /// Returns platformBrightness 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
  /// any property of the ancestor [MediaQuery] changes.
  static Brightness platformBrightnessOf(BuildContext context) {
    return MediaQuery.of(context, nullOk: true)?.platformBrightness ?? Brightness.light;
  }

844 845 846 847 848 849 850 851 852 853 854
  /// Returns highContrast for the nearest MediaQuery ancestor or false, if no
  /// such ancestor exists.
  ///
  /// See also:
  ///
  ///  * [MediaQueryData.highContrast], which indicates the platform's
  ///    desire to increase contrast.
  static bool highContrastOf(BuildContext context) {
    return MediaQuery.of(context, nullOk: true)?.highContrast ?? false;
  }

855 856 857 858 859 860
  /// Returns the boldText accessibility setting for the nearest MediaQuery
  /// ancestor, or false if no such ancestor exists.
  static bool boldTextOverride(BuildContext context) {
    return MediaQuery.of(context, nullOk: true)?.boldText ?? false;
  }

861
  @override
862
  bool updateShouldNotify(MediaQuery oldWidget) => data != oldWidget.data;
863

864
  @override
865 866
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
867
    properties.add(DiagnosticsProperty<MediaQueryData>('data', data, showName: false));
868 869
  }
}
870

871
/// Describes the navigation mode to be set by a [MediaQuery] widget.
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
///
/// The different modes indicate the type of navigation to be used in a widget
/// subtree for those widgets sensitive to it.
///
/// Use `MediaQuery.of(context).navigationMode` to determine the navigation mode
/// in effect for the given context. Use a [MediaQuery] widget to set the
/// navigation mode for its descendant widgets.
enum NavigationMode {
  /// This indicates a traditional keyboard-and-mouse navigation modality.
  ///
  /// This navigation mode is where the arrow keys can be used for secondary
  /// modification operations, like moving sliders or cursors, and disabled
  /// controls will lose focus and not be traversable.
  traditional,

  /// This indicates a directional-based navigation mode.
  ///
  /// This navigation mode indicates that arrow keys should be reserved for
  /// navigation operations, and secondary modifications operations, like moving
  /// sliders or cursors, will use alternative bindings or be disabled.
  ///
  /// Some behaviors are also affected by this mode. For instance, disabled
  /// controls will retain focus when disabled, and will be able to receive
  /// focus (although they remain disabled) when traversed.
  directional,
}