text.dart 10.7 KB
Newer Older
1 2 3 4
// Copyright 2016 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/foundation.dart';
6 7 8 9 10 11 12 13 14

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

/// The text style to apply to descendant [Text] widgets without explicit style.
class DefaultTextStyle extends InheritedWidget {
  /// Creates a default text style for the given subtree.
  ///
15
  /// Consider using [DefaultTextStyle.merge] to inherit styling information
16
  /// from the current default text style for a given [BuildContext].
17 18 19 20 21 22 23 24
  ///
  /// The [style] and [child] arguments are required and must not be null.
  ///
  /// The [softWrap] and [overflow] arguments must not be null (though they do
  /// have default values).
  ///
  /// The [maxLines] property may be null (and indeed defaults to null), but if
  /// it is not null, it must be greater than zero.
25
  const DefaultTextStyle({
26 27 28 29 30
    Key key,
    @required this.style,
    this.textAlign,
    this.softWrap: true,
    this.overflow: TextOverflow.clip,
31
    this.maxLines,
32
    @required Widget child,
33 34 35
  }) : assert(style != null),
       assert(softWrap != null),
       assert(overflow != null),
36
       assert(maxLines == null || maxLines > 0),
37 38
       assert(child != null),
       super(key: key, child: child);
39 40 41 42

  /// A const-constructible default text style that provides fallback values.
  ///
  /// Returned from [of] when the given [BuildContext] doesn't have an enclosing default text style.
43 44 45
  ///
  /// This constructor creates a [DefaultTextStyle] that lacks a [child], which
  /// means the constructed value cannot be incorporated into the tree.
46 47 48 49
  const DefaultTextStyle.fallback()
    : style = const TextStyle(),
      textAlign = null,
      softWrap = true,
50
      maxLines = null,
51 52
      overflow = TextOverflow.clip;

53 54
  /// Creates a default text style that overrides the text styles in scope at
  /// this point in the widget tree.
55 56
  ///
  /// The given [style] is merged with the [style] from the default text style
57 58 59
  /// for the [BuildContext] where the widget is inserted, and any of the other
  /// arguments that are not null replace the corresponding properties on that
  /// same default text style.
60 61 62 63 64 65 66 67 68
  ///
  /// This constructor cannot be used to override the [maxLines] property of the
  /// ancestor with the value null, since null here is used to mean "defer to
  /// ancestor". To replace a non-null [maxLines] from an ancestor with the null
  /// value (to remove the restriction on number of lines), manually obtain the
  /// ambient [DefaultTextStyle] using [DefaultTextStyle.of], then create a new
  /// [DefaultTextStyle] using the [new DefaultTextStyle] constructor directly.
  /// See the source below for an example of how to do this (since that's
  /// essentially what this constructor does).
69
  static Widget merge({
70 71 72 73 74
    Key key,
    TextStyle style,
    TextAlign textAlign,
    bool softWrap,
    TextOverflow overflow,
75
    int maxLines,
76
    @required Widget child,
77 78
  }) {
    assert(child != null);
79 80 81 82 83 84 85 86 87 88
    return new Builder(
      builder: (BuildContext context) {
        final DefaultTextStyle parent = DefaultTextStyle.of(context);
        return new DefaultTextStyle(
          key: key,
          style: parent.style.merge(style),
          textAlign: textAlign ?? parent.textAlign,
          softWrap: softWrap ?? parent.softWrap,
          overflow: overflow ?? parent.overflow,
          maxLines: maxLines ?? parent.maxLines,
89
          child: child,
90 91
        );
      },
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    );
  }

  /// The text style to apply.
  final TextStyle style;

  /// How the text should be aligned horizontally.
  final TextAlign textAlign;

  /// Whether the text should break at soft line breaks.
  ///
  /// If false, the glyphs in the text will be positioned as if there was unlimited horizontal space.
  final bool softWrap;

  /// How visual overflow should be handled.
  final TextOverflow overflow;

109 110 111
  /// An optional maximum number of lines for the text to span, wrapping if necessary.
  /// If the text exceeds the given number of lines, it will be truncated according
  /// to [overflow].
112 113 114 115 116 117
  ///
  /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the
  /// edge of the box.
  ///
  /// If this is non-null, it will override even explicit null values of
  /// [Text.maxLines].
118 119
  final int maxLines;

120 121 122 123
  /// The closest instance of this class that encloses the given context.
  ///
  /// If no such instance exists, returns an instance created by
  /// [DefaultTextStyle.fallback], which contains fallback values.
124 125 126 127 128 129
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// DefaultTextStyle style = DefaultTextStyle.of(context);
  /// ```
130 131 132 133 134
  static DefaultTextStyle of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(DefaultTextStyle) ?? const DefaultTextStyle.fallback();
  }

  @override
135 136 137 138 139 140 141
  bool updateShouldNotify(DefaultTextStyle old) {
    return style != old.style ||
        textAlign != old.textAlign ||
        softWrap != old.softWrap ||
        overflow != old.overflow ||
        maxLines != old.maxLines;
  }
142 143

  @override
144
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
145 146
    super.debugFillProperties(description);
    style?.debugFillProperties(description);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
  }
}

/// A run of text with a single style.
///
/// The [Text] widget displays a string of text with single style. The string
/// might break across multiple lines or might all be displayed on the same line
/// depending on the layout constraints.
///
/// The [style] argument is optional. When omitted, the text will use the style
/// from the closest enclosing [DefaultTextStyle]. If the given style's
/// [TextStyle.inherit] property is true, the given style will be merged with
/// the closest enclosing [DefaultTextStyle]. This merging behavior is useful,
/// for example, to make the text bold while using the default font family and
/// size.
///
/// To display text that uses multiple styles (e.g., a paragraph with some bold
/// words), use [RichText].
///
166 167 168 169
/// ## Sample code
///
/// ```dart
/// new Text(
170
///   'Hello, $_name! How are you?',
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
///   textAlign: TextAlign.center,
///   overflow: TextOverflow.ellipsis,
///   style: new TextStyle(fontWeight: FontWeight.bold),
/// )
/// ```
///
/// ## Interactivity
///
/// To make [Text] react to touch events, wrap it in a [GestureDetector] widget
/// with a [GestureDetector.onTap] handler.
///
/// In a material design application, consider using a [FlatButton] instead, or
/// if that isn't appropriate, at least using an [InkWell] instead of
/// [GestureDetector].
///
/// To make sections of the text interactive, use [RichText] and specify a
/// [TapGestureRecognizer] as the [TextSpan.recognizer] of the relevant part of
/// the text.
///
190 191
/// See also:
///
192 193
///  * [RichText], which gives you more control over the text styles.
///  * [DefaultTextStyle], which sets default styles for [Text] widgets.
194 195 196 197 198
class Text extends StatelessWidget {
  /// Creates a text widget.
  ///
  /// If the [style] argument is null, the text will use the style from the
  /// closest enclosing [DefaultTextStyle].
199
  const Text(this.data, {
200 201 202
    Key key,
    this.style,
    this.textAlign,
Ian Hickson's avatar
Ian Hickson committed
203
    this.textDirection,
204 205
    this.softWrap,
    this.overflow,
206 207
    this.textScaleFactor,
    this.maxLines,
208 209
  }) : assert(data != null),
       super(key: key);
210 211 212 213 214 215 216 217 218 219 220 221 222 223

  /// The text to display.
  final String data;

  /// If non-null, the style to use for this text.
  ///
  /// If the style's "inherit" property is true, the style will be merged with
  /// the closest enclosing [DefaultTextStyle]. Otherwise, the style will
  /// replace the closest enclosing [DefaultTextStyle].
  final TextStyle style;

  /// How the text should be aligned horizontally.
  final TextAlign textAlign;

Ian Hickson's avatar
Ian Hickson committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  /// The directionality of the text.
  ///
  /// This decides how [textAlign] values like [TextAlign.start] and
  /// [TextAlign.end] are interpreted.
  ///
  /// This is also used to disambiguate how to render bidirectional text. For
  /// example, if the [data] is an English phrase followed by a Hebrew phrase,
  /// in a [TextDirection.ltr] context the English phrase will be on the left
  /// and the Hebrew phrase to its right, while in a [TextDirection.rtl]
  /// context, the English phrase will be on the right and the Hebrow phrase on
  /// its left.
  ///
  /// Defaults to the ambient [Directionality], if any.
  final TextDirection textDirection;

239 240 241 242 243 244 245 246 247 248 249 250 251
  /// Whether the text should break at soft line breaks.
  ///
  /// If false, the glyphs in the text will be positioned as if there was unlimited horizontal space.
  final bool softWrap;

  /// How visual overflow should be handled.
  final TextOverflow overflow;

  /// The number of font pixels for each logical pixel.
  ///
  /// For example, if the text scale factor is 1.5, text will be 50% larger than
  /// the specified font size.
  ///
252 253
  /// The value given to the constructor as textScaleFactor.  If null, will
  /// use the [MediaQueryData.textScaleFactor] obtained from the ambient
254
  /// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope.
255 256
  final double textScaleFactor;

257
  /// An optional maximum number of lines for the text to span, wrapping if necessary.
258 259
  /// If the text exceeds the given number of lines, it will be truncated according
  /// to [overflow].
260 261 262 263 264 265 266 267
  ///
  /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the
  /// edge of the box.
  ///
  /// If this is null, but there is an ambient [DefaultTextStyle] that specifies
  /// an explicit number for its [DefaultTextStyle.maxLines], then the
  /// [DefaultTextStyle] value will take precedence. You can use a [RichText]
  /// widget directly to entirely override the [DefaultTextStyle].
268 269
  final int maxLines;

270 271
  @override
  Widget build(BuildContext context) {
272
    final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
273 274 275 276
    TextStyle effectiveTextStyle = style;
    if (style == null || style.inherit)
      effectiveTextStyle = defaultTextStyle.style.merge(style);
    return new RichText(
Ian Hickson's avatar
Ian Hickson committed
277 278
      textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
      textDirection: textDirection, // RichText uses Directionality.of to obtain a default if this is null.
279 280
      softWrap: softWrap ?? defaultTextStyle.softWrap,
      overflow: overflow ?? defaultTextStyle.overflow,
281
      textScaleFactor: textScaleFactor ?? MediaQuery.of(context, nullOk: true)?.textScaleFactor ?? 1.0,
282
      maxLines: maxLines ?? defaultTextStyle.maxLines,
283 284
      text: new TextSpan(
        style: effectiveTextStyle,
285
        text: data,
286 287 288 289 290
      )
    );
  }

  @override
291
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
292 293 294
    super.debugFillProperties(description);
    description.add(new StringProperty('data', data, showName: false));
    style?.debugFillProperties(description);
295 296
  }
}