theme.dart 8.08 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.

xster's avatar
xster committed
5
import 'package:flutter/cupertino.dart';
6
import 'package:flutter/foundation.dart';
7

8
import 'material_localizations.dart';
9
import 'theme_data.dart';
10
import 'typography.dart';
11

12
export 'theme_data.dart' show Brightness, ThemeData;
13

14
/// The duration over which theme changes animate by default.
15
const Duration kThemeAnimationDuration = Duration(milliseconds: 200);
16

17
/// Applies a theme to descendant widgets.
18
///
19 20 21 22 23 24
/// A theme describes the colors and typographic choices of an application.
///
/// Descendant widgets obtain the current theme's [ThemeData] object using
/// [Theme.of]. When a widget uses [Theme.of], it is automatically rebuilt if
/// the theme later changes, so that the changes can be applied.
///
25 26 27
/// The [Theme] widget implies an [IconTheme] widget, set to the value of the
/// [ThemeData.iconTheme] of the [data] for the [Theme].
///
28 29
/// See also:
///
30 31 32 33 34
///  * [ThemeData], which describes the actual configuration of a theme.
///  * [AnimatedTheme], which animates the [ThemeData] when it changes rather
///    than changing the theme all at once.
///  * [MaterialApp], which includes an [AnimatedTheme] widget configured via
///    the [MaterialApp.theme] argument.
35
class Theme extends StatelessWidget {
36 37
  /// Applies the given theme [data] to [child].
  ///
38
  /// The [data] and [child] arguments must not be null.
39
  const Theme({
40 41 42
    Key? key,
    required this.data,
    required this.child,
43 44
  }) : assert(child != null),
       assert(data != null),
45
       super(key: key);
46

47
  /// Specifies the color and typography values for descendant widgets.
48 49
  final ThemeData data;

50
  /// The widget below this widget in the tree.
51
  ///
52
  /// {@macro flutter.widgets.ProxyWidget.child}
53 54
  final Widget child;

55
  static final ThemeData _kFallbackTheme = ThemeData.fallback();
56

57 58
  /// The data from the closest [Theme] instance that encloses the given
  /// context.
59
  ///
60 61 62 63
  /// If the given context is enclosed in a [Localizations] widget providing
  /// [MaterialLocalizations], the returned data is localized according to the
  /// nearest available [MaterialLocalizations].
  ///
64 65
  /// Defaults to [new ThemeData.fallback] if there is no [Theme] in the given
  /// build context.
66
  ///
67 68 69 70 71
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// @override
  /// Widget build(BuildContext context) {
72
  ///   return Text(
73
  ///     'Example',
74
  ///     style: Theme.of(context).textTheme.headline6,
75 76 77 78 79 80 81 82 83 84 85 86 87 88
  ///   );
  /// }
  /// ```
  ///
  /// When the [Theme] is actually created in the same `build` function
  /// (possibly indirectly, e.g. as part of a [MaterialApp]), the `context`
  /// argument to the `build` function can't be used to find the [Theme] (since
  /// it's "above" the widget being returned). In such cases, the following
  /// technique with a [Builder] can be used to provide a new scope with a
  /// [BuildContext] that is "under" the [Theme]:
  ///
  /// ```dart
  /// @override
  /// Widget build(BuildContext context) {
89 90 91
  ///   return MaterialApp(
  ///     theme: ThemeData.light(),
  ///     body: Builder(
92 93 94
  ///       // Create an inner BuildContext so that we can refer to
  ///       // the Theme with Theme.of().
  ///       builder: (BuildContext context) {
95 96
  ///         return Center(
  ///           child: Text(
97
  ///             'Example',
98
  ///             style: Theme.of(context).textTheme.headline6,
99 100 101 102 103 104 105
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
106
  static ThemeData of(BuildContext context) {
107
    final _InheritedTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedTheme>();
108
    final MaterialLocalizations? localizations = Localizations.of<MaterialLocalizations>(context, MaterialLocalizations);
109
    final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike;
110
    final ThemeData theme = inheritedTheme?.theme.data ?? _kFallbackTheme;
111
    return ThemeData.localize(theme, theme.typography.geometryThemeFor(category));
112 113
  }

114
  @override
115
  Widget build(BuildContext context) {
116
    return _InheritedTheme(
117
      theme: this,
118 119 120 121 122 123 124 125 126
      child: CupertinoTheme(
        // We're using a MaterialBasedCupertinoThemeData here instead of a
        // CupertinoThemeData because it defers some properties to the Material
        // ThemeData.
        data: MaterialBasedCupertinoThemeData(
          materialTheme: data,
        ),
        child: IconTheme(
          data: data.iconTheme,
xster's avatar
xster committed
127 128
          child: child,
        ),
129
      ),
130 131
    );
  }
Hixie's avatar
Hixie committed
132

133
  @override
134 135
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
136
    properties.add(DiagnosticsProperty<ThemeData>('data', data, showName: false));
Hixie's avatar
Hixie committed
137
  }
138
}
139

140
class _InheritedTheme extends InheritedTheme {
141
  const _InheritedTheme({
142 143 144
    Key? key,
    required this.theme,
    required Widget child,
145 146 147 148 149
  }) : assert(theme != null),
       super(key: key, child: child);

  final Theme theme;

150 151
  @override
  Widget wrap(BuildContext context, Widget child) {
152
    return Theme(data: theme.data, child: child);
153 154
  }

155
  @override
156
  bool updateShouldNotify(_InheritedTheme old) => theme.data != old.theme.data;
157 158
}

159 160 161 162 163 164
/// An interpolation between two [ThemeData]s.
///
/// This class specializes the interpolation of [Tween<ThemeData>] to call the
/// [ThemeData.lerp] method.
///
/// See [Tween] for a discussion on how to use interpolation objects.
165
class ThemeDataTween extends Tween<ThemeData> {
166 167 168 169 170
  /// Creates a [ThemeData] tween.
  ///
  /// The [begin] and [end] properties must be non-null before the tween is
  /// first used, but the arguments can be null if the values are going to be
  /// filled in later.
171
  ThemeDataTween({ ThemeData? begin, ThemeData? end }) : super(begin: begin, end: end);
172

173
  @override
174
  ThemeData lerp(double t) => ThemeData.lerp(begin!, end!, t);
175 176
}

177
/// Animated version of [Theme] which automatically transitions the colors,
178
/// etc, over a given duration whenever the given theme changes.
179
///
180 181 182 183
/// Here's an illustration of what using this widget looks like, using a [curve]
/// of [Curves.elasticInOut].
/// {@animation 250 266 https://flutter.github.io/assets-for-api-docs/assets/widgets/animated_theme.mp4}
///
184 185
/// See also:
///
186 187 188 189 190
///  * [Theme], which [AnimatedTheme] uses to actually apply the interpolated
///    theme.
///  * [ThemeData], which describes the actual configuration of a theme.
///  * [MaterialApp], which includes an [AnimatedTheme] widget configured via
///    the [MaterialApp.theme] argument.
191
class AnimatedTheme extends ImplicitlyAnimatedWidget {
192 193
  /// Creates an animated theme.
  ///
194 195
  /// By default, the theme transition uses a linear curve. The [data] and
  /// [child] arguments must not be null.
196
  const AnimatedTheme({
197 198
    Key? key,
    required this.data,
199 200
    Curve curve = Curves.linear,
    Duration duration = kThemeAnimationDuration,
201 202
    VoidCallback? onEnd,
    required this.child,
203 204
  }) : assert(child != null),
       assert(data != null),
205
       super(key: key, curve: curve, duration: duration, onEnd: onEnd);
206

207
  /// Specifies the color and typography values for descendant widgets.
208 209
  final ThemeData data;

210
  /// The widget below this widget in the tree.
211
  ///
212
  /// {@macro flutter.widgets.ProxyWidget.child}
213 214
  final Widget child;

215
  @override
216
  _AnimatedThemeState createState() => _AnimatedThemeState();
217 218 219
}

class _AnimatedThemeState extends AnimatedWidgetBaseState<AnimatedTheme> {
220
  ThemeDataTween? _data;
221

222
  @override
223
  void forEachTween(TweenVisitor<dynamic> visitor) {
224
    // TODO(ianh): Use constructor tear-offs when it becomes possible, https://github.com/dart-lang/sdk/issues/10659
225
    _data = visitor(_data, widget.data, (dynamic value) => ThemeDataTween(begin: value as ThemeData))! as ThemeDataTween;
226 227
  }

228
  @override
229
  Widget build(BuildContext context) {
230
    return Theme(
231
      child: widget.child,
232
      data: _data!.evaluate(animation),
233 234 235
    );
  }

236
  @override
237
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
238
    super.debugFillProperties(description);
239
    description.add(DiagnosticsProperty<ThemeDataTween>('data', _data, showName: false, defaultValue: null));
240 241
  }
}