media_query.dart 1.99 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 20
  const MediaQueryData({ this.size });

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

24
  /// The orientation of the media (e.g., whether the device is in landscape or portrait mode).
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  Orientation get orientation {
    return size.width > size.height ? Orientation.landscape : Orientation.portrait;
  }

  bool operator==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
    MediaQueryData typedOther = other;
    return typedOther.size == size;
  }

  int get hashCode => size.hashCode;

  String toString() => '$runtimeType($size, $orientation)';
}

41
/// Establishes a subtree in which media queries resolve to the given data.
42 43 44 45 46 47 48 49 50 51
class MediaQuery extends InheritedWidget {
  MediaQuery({
    Key key,
    this.data,
    Widget child
  }) : super(key: key, child: child) {
    assert(child != null);
    assert(data != null);
  }

52
  /// The result of media queries in this subtree.
53 54
  final MediaQueryData data;

55
  /// The data from the closest instance of this class that encloses the given context.
56 57 58 59
  ///
  /// 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.
60
  static MediaQueryData of(BuildContext context) {
Hixie's avatar
Hixie committed
61
    MediaQuery query = context.inheritFromWidgetOfType(MediaQuery);
62 63 64 65 66 67 68 69 70 71
    return query == null ? null : query.data;
  }

  bool updateShouldNotify(MediaQuery old) => data != old.data;

  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('$data');
  }
}