theme.dart 2.53 KB
Newer Older
1 2 3 4
// 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.

5
import 'package:flutter/widgets.dart';
6

7 8 9
import 'theme_data.dart';

export 'theme_data.dart' show ThemeData, ThemeBrightness;
10

11 12
const kThemeAnimationDuration = const Duration(milliseconds: 200);

13
class Theme extends InheritedWidget {
14
  Theme({
15
    Key key,
16 17 18 19 20 21 22 23 24 25 26
    this.data,
    Widget child
  }) : super(key: key, child: child) {
    assert(child != null);
    assert(data != null);
  }

  final ThemeData data;

  static final ThemeData _kFallbackTheme = new ThemeData.fallback();

27 28 29
  /// The data from the closest instance of this class that encloses the given context.
  ///
  /// Defaults to the fallback theme data if none exists.
30
  static ThemeData of(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
31
    Theme theme = context.inheritFromWidgetOfExactType(Theme);
32
    return theme?.data ?? _kFallbackTheme;
33 34
  }

35
  bool updateShouldNotify(Theme old) => data != old.data;
Hixie's avatar
Hixie committed
36 37 38 39 40

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

43 44 45
/// An animated value that interpolates [ThemeData]s.
class ThemeDataTween extends Tween<ThemeData> {
  ThemeDataTween({ ThemeData begin, ThemeData end }) : super(begin: begin, end: end);
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

  ThemeData lerp(double t) => ThemeData.lerp(begin, end, t);
}

/// Animated version of [Theme] which automatically transitions the colours,
/// etc, over a given duration whenever the given theme changes.
class AnimatedTheme extends AnimatedWidgetBase {
  AnimatedTheme({
    Key key,
    this.data,
    Curve curve: Curves.linear,
    Duration duration,
    this.child
  }) : super(key: key, curve: curve, duration: duration) {
    assert(child != null);
    assert(data != null);
  }

  final ThemeData data;

  final Widget child;

  _AnimatedThemeState createState() => new _AnimatedThemeState();
}

class _AnimatedThemeState extends AnimatedWidgetBaseState<AnimatedTheme> {
72
  ThemeDataTween _data;
73

74
  void forEachTween(TweenVisitor visitor) {
75
    // TODO(ianh): Use constructor tear-offs when it becomes possible
76
    _data = visitor(_data, config.data, (dynamic value) => new ThemeDataTween(begin: value));
77 78 79 80 81 82
    assert(_data != null);
  }

  Widget build(BuildContext context) {
    return new Theme(
      child: config.child,
83
      data: _data.evaluate(animation)
84 85 86 87 88 89 90 91 92
    );
  }

  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    if (_data != null)
      description.add('$_data');
  }
}