media_query.dart 2.59 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'basic.dart';
import 'framework.dart';

8 9 10 11
/// Whether in portrait or landscape.
enum Orientation {
  /// Taller than wide.
  portrait,
12

13 14 15
  /// Wider than tall.
  landscape
}
16

17 18
/// The result of a media query.
class MediaQueryData {
19
  const MediaQueryData({ this.size, this.devicePixelRatio, this.padding });
20

21
  /// The size of the media (e.g, the size of the screen).
22 23
  final Size size;

24 25 26 27 28
  /// 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;

29
  /// The padding around the edges of the media (e.g., the screen).
30
  final EdgeInsets padding;
31

32
  /// The orientation of the media (e.g., whether the device is in landscape or portrait mode).
33 34 35 36
  Orientation get orientation {
    return size.width > size.height ? Orientation.landscape : Orientation.portrait;
  }

37
  @override
38 39 40 41
  bool operator==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
    MediaQueryData typedOther = other;
42
    return typedOther.size == size
43 44
        && typedOther.padding == padding
        && typedOther.devicePixelRatio == devicePixelRatio;
45 46
  }

47
  @override
48 49 50 51 52
  int get hashCode => hashValues(
    size.hashCode,
    padding.hashCode,
    devicePixelRatio.hashCode
  );
53

54
  @override
55 56 57
  String toString() => '$runtimeType($size, $orientation)';
}

58
/// Establishes a subtree in which media queries resolve to the given data.
59 60 61 62 63 64 65 66 67 68
class MediaQuery extends InheritedWidget {
  MediaQuery({
    Key key,
    this.data,
    Widget child
  }) : super(key: key, child: child) {
    assert(child != null);
    assert(data != null);
  }

69
  /// The result of media queries in this subtree.
70 71
  final MediaQueryData data;

72
  /// The data from the closest instance of this class that encloses the given context.
73 74 75 76
  ///
  /// You can use this function to query the size an orientation of the screen.
  /// When that information changes, your widget will be scheduled to be rebuilt,
  /// keeping your widget up-to-date.
77
  static MediaQueryData of(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
78
    MediaQuery query = context.inheritFromWidgetOfExactType(MediaQuery);
79 80 81
    return query == null ? null : query.data;
  }

82
  @override
83 84
  bool updateShouldNotify(MediaQuery old) => data != old.data;

85
  @override
86 87 88 89 90
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('$data');
  }
}