theme.dart 8.05 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
/// A theme describes the colors and typographic choices of an application.
///
21 22
/// {@youtube 560 315 https://www.youtube.com/watch?v=oTvQDJOBXmM}
///
23 24 25 26
/// 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.
///
27 28 29
/// The [Theme] widget implies an [IconTheme] widget, set to the value of the
/// [ThemeData.iconTheme] of the [data] for the [Theme].
///
30 31
/// See also:
///
32 33 34 35 36
///  * [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.
37
class Theme extends StatelessWidget {
38 39
  /// Applies the given theme [data] to [child].
  ///
40
  /// The [data] and [child] arguments must not be null.
41
  const Theme({
42 43 44
    Key? key,
    required this.data,
    required this.child,
45 46
  }) : assert(child != null),
       assert(data != null),
47
       super(key: key);
48

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

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

57
  static final ThemeData _kFallbackTheme = ThemeData.fallback();
58

59 60
  /// The data from the closest [Theme] instance that encloses the given
  /// context.
61
  ///
62 63 64 65
  /// If the given context is enclosed in a [Localizations] widget providing
  /// [MaterialLocalizations], the returned data is localized according to the
  /// nearest available [MaterialLocalizations].
  ///
66
  /// Defaults to [ThemeData.fallback] if there is no [Theme] in the given
67
  /// build context.
68
  ///
69 70 71 72 73
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// @override
  /// Widget build(BuildContext context) {
74
  ///   return Text(
75
  ///     'Example',
76
  ///     style: Theme.of(context).textTheme.headline6,
77 78 79 80 81 82 83 84 85 86 87 88 89 90
  ///   );
  /// }
  /// ```
  ///
  /// 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) {
91 92 93
  ///   return MaterialApp(
  ///     theme: ThemeData.light(),
  ///     body: Builder(
94 95 96
  ///       // Create an inner BuildContext so that we can refer to
  ///       // the Theme with Theme.of().
  ///       builder: (BuildContext context) {
97 98
  ///         return Center(
  ///           child: Text(
99
  ///             'Example',
100
  ///             style: Theme.of(context).textTheme.headline6,
101 102 103 104 105 106 107
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
108
  static ThemeData of(BuildContext context) {
109
    final _InheritedTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedTheme>();
110
    final MaterialLocalizations? localizations = Localizations.of<MaterialLocalizations>(context, MaterialLocalizations);
111
    final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike;
112
    final ThemeData theme = inheritedTheme?.theme.data ?? _kFallbackTheme;
113
    return ThemeData.localize(theme, theme.typography.geometryThemeFor(category));
114 115
  }

116
  @override
117
  Widget build(BuildContext context) {
118
    return _InheritedTheme(
119
      theme: this,
120 121 122 123 124 125 126 127 128
      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
129 130
          child: child,
        ),
131
      ),
132 133
    );
  }
Hixie's avatar
Hixie committed
134

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

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

  final Theme theme;

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

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

161 162 163 164 165 166
/// 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.
167
class ThemeDataTween extends Tween<ThemeData> {
168 169 170 171 172
  /// 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.
173
  ThemeDataTween({ ThemeData? begin, ThemeData? end }) : super(begin: begin, end: end);
174

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

179
/// Animated version of [Theme] which automatically transitions the colors,
180
/// etc, over a given duration whenever the given theme changes.
181
///
182 183 184 185
/// 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}
///
186 187
/// See also:
///
188 189 190 191 192
///  * [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.
193
class AnimatedTheme extends ImplicitlyAnimatedWidget {
194 195
  /// Creates an animated theme.
  ///
196 197
  /// By default, the theme transition uses a linear curve. The [data] and
  /// [child] arguments must not be null.
198
  const AnimatedTheme({
199 200
    Key? key,
    required this.data,
201 202
    Curve curve = Curves.linear,
    Duration duration = kThemeAnimationDuration,
203 204
    VoidCallback? onEnd,
    required this.child,
205 206
  }) : assert(child != null),
       assert(data != null),
207
       super(key: key, curve: curve, duration: duration, onEnd: onEnd);
208

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

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

217
  @override
218
  AnimatedWidgetBaseState<AnimatedTheme> createState() => _AnimatedThemeState();
219 220 221
}

class _AnimatedThemeState extends AnimatedWidgetBaseState<AnimatedTheme> {
222
  ThemeDataTween? _data;
223

224
  @override
225
  void forEachTween(TweenVisitor<dynamic> visitor) {
226
    _data = visitor(_data, widget.data, (dynamic value) => ThemeDataTween(begin: value as ThemeData))! as ThemeDataTween;
227 228
  }

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

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