text_style.dart 59.6 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.

5
import 'dart:ui' as ui show ParagraphStyle, TextStyle, StrutStyle, lerpDouble, Shadow, FontFeature, FontVariation, TextHeightBehavior, TextLeadingDistribution;
6

7 8
import 'package:flutter/foundation.dart';

9
import 'basic_types.dart';
10
import 'colors.dart';
11
import 'strut_style.dart';
12
import 'text_painter.dart';
13

14 15
const String _kDefaultDebugLabel = 'unknown';

16
const String _kColorForegroundWarning = 'Cannot provide both a color and a foreground\n'
17
    'The color argument is just a shorthand for "foreground: Paint()..color = color".';
18 19

const String _kColorBackgroundWarning = 'Cannot provide both a backgroundColor and a background\n'
20
    'The backgroundColor argument is just a shorthand for "background: Paint()..color = color".';
21

22 23 24 25 26
// The default font size if none is specified. This should be kept in
// sync with the default values in text_painter.dart, as well as the
// defaults set in the engine (eg, LibTxt's text_style.h, paragraph_style.h).
const double _kDefaultFontSize = 14.0;

27
// Examples can assume:
28
// late BuildContext context;
29

30
/// An immutable style describing how to format and paint text.
31
///
32
/// ### Bold
33
///
34
/// {@tool snippet}
35 36 37 38
/// Here, a single line of text in a [Text] widget is given a specific style
/// override. The style is mixed with the ambient [DefaultTextStyle] by the
/// [Text] widget.
///
39
/// ![Applying the style in this way creates bold text.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_bold.png)
40
///
41
/// ```dart
42
/// const Text(
43
///   'No, we need bold strokes. We need this plan.',
44
///   style: TextStyle(fontWeight: FontWeight.bold),
45 46
/// )
/// ```
47
/// {@end-tool}
48
///
49
/// ### Italics
50
///
51
/// {@tool snippet}
52 53
/// As in the previous example, the [Text] widget is given a specific style
/// override which is implicitly mixed with the ambient [DefaultTextStyle].
54
///
55
/// ![This results in italicized text.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_italics.png)
56
///
57
/// ```dart
58
/// const Text(
59
///   "Welcome to the present, we're running a real nation.",
60
///   style: TextStyle(fontStyle: FontStyle.italic),
61 62
/// )
/// ```
63
/// {@end-tool}
64
///
65
/// ### Opacity and Color
66
///
67 68 69 70 71 72 73 74 75
/// Each line here is progressively more opaque. The base color is
/// [material.Colors.black], and [Color.withOpacity] is used to create a
/// derivative color with the desired opacity. The root [TextSpan] for this
/// [RichText] widget is explicitly given the ambient [DefaultTextStyle], since
/// [RichText] does not do that automatically. The inner [TextStyle] objects are
/// implicitly mixed with the parent [TextSpan]'s [TextSpan.style].
///
/// If [color] is specified, [foreground] must be null and vice versa. [color] is
/// treated as a shorthand for `Paint()..color = color`.
76
///
77 78 79 80
/// If [backgroundColor] is specified, [background] must be null and vice versa.
/// The [backgroundColor] is treated as a shorthand for
/// `background: Paint()..color = backgroundColor`.
///
81
/// ![This results in three lines of text that go from lighter to darker in color.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_opacity_and_color.png)
82
///
83
/// ```dart
84 85 86
/// RichText(
///   text: TextSpan(
///     style: DefaultTextStyle.of(context).style,
87
///     children: <TextSpan>[
88
///       TextSpan(
89
///         text: "You don't have the votes.\n",
90
///         style: TextStyle(color: Colors.black.withOpacity(0.6)),
91
///       ),
92
///       TextSpan(
93
///         text: "You don't have the votes!\n",
94
///         style: TextStyle(color: Colors.black.withOpacity(0.8)),
95
///       ),
96
///       TextSpan(
97
///         text: "You're gonna need congressional approval and you don't have the votes!\n",
98
///         style: TextStyle(color: Colors.black.withOpacity(1.0)),
99 100 101 102 103 104
///       ),
///     ],
///   ),
/// )
/// ```
///
105
/// ### Size
106
///
107
/// {@tool snippet}
108 109 110
/// In this example, the ambient [DefaultTextStyle] is explicitly manipulated to
/// obtain a [TextStyle] that doubles the default font size.
///
111
/// ![This results in text that is twice as large as normal.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_size.png)
112
///
113
/// ```dart
114
/// Text(
115
///   "These are wise words, enterprising men quote 'em.",
116 117 118
///   style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0),
/// )
/// ```
119
/// {@end-tool}
120
///
121
/// ### Line height
122
///
123 124 125 126 127
/// By default, text will layout with line height as defined by the font.
/// Font-metrics defined line height may be taller or shorter than the font size.
/// The [height] property allows manual adjustment of the height of the line as
/// a multiple of [fontSize]. For most fonts, setting [height] to 1.0 is not
/// the same as omitting or setting height to null. The following diagram
128
/// illustrates the difference between the font-metrics-defined line height and
129 130
/// the line height produced with `height: 1.0` (also known as the EM-square):
///
131
/// ![With the font-metrics-defined line height, there is space between lines appropriate for the font, whereas the EM-square is only the height required to hold most of the characters.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_height_diagram.png)
132
///
133
/// {@tool snippet}
134
/// The [height] property can be used to change the line height. Here, the line
135
/// height is set to 5 times the font size, so that the text is very spaced out.
136 137
/// Since the `fontSize` is set to 10, the final height of the line is
/// 50 pixels.
138 139
///
/// ```dart
140
/// const Text(
141 142
///   'Ladies and gentlemen, you coulda been anywhere in the world tonight, but you’re here with us in New York City.',
///   style: TextStyle(height: 5, fontSize: 10),
143 144
/// )
/// ```
145
/// {@end-tool}
146
///
147 148
/// Examples of the resulting heights from different values of `TextStyle.height`:
///
149
/// ![Since the explicit line height is applied as a scale factor on the font-metrics-defined line height, the gap above the text grows faster, as the height grows, than the gap below the text.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_height_comparison_diagram.png)
150
///
151 152
/// See [StrutStyle] for further control of line height at the paragraph level.
///
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
/// ### Leading Distribution and Trimming
///
/// [Leading](https://en.wikipedia.org/wiki/Leading) is the vertical space
/// between glyphs from adjacent lines. Quantitatively, it is the line height
/// (see the previous section) subtracted by the font's ascent and descent.
/// It's possible to have a negative `Leading` if [height] is sufficiently
/// small.
///
/// When the [height] multiplier is null, `leading` and how it is distributed
/// is up to the font's
/// [metrics](https://en.wikipedia.org/wiki/Typeface#Font_metrics).
/// When the [height] multiplier is specified, the exact behavior can be
/// configured via [leadingDistribution] and [TextPainter.textHeightBehavior].
///
/// ![In configuration 1 the line height is divided by the alphabetic baseline proportionally to the font's ascent and descent, in configuration 3 the glyphs are roughly centered within the line height, configuration 2 is similar to configuration 1 except the Text Top guide on the same line as the font's ascent](https://flutter.github.io/assets-for-api-docs/assets/painting/text_height_breakdown.png)
///
/// Above is a side-by-side comparison of different [leadingDistribution] and
/// [TextPainter.textHeightBehavior] combinations.
///
///  * Configuration 1: The default. [leadingDistribution] is set to [TextLeadingDistribution.proportional].
///  * Configuration 2: same as Configuration 1, except [TextHeightBehavior.applyHeightToFirstAscent] is set to false.
///  * Configuration 3: [leadingDistribution] is set to [TextLeadingDistribution.even].
///  * Configuration 4: same as Configuration 3, except [TextHeightBehavior.applyHeightToLastDescent] is set to false.
///
/// The [leadingDistribution] property controls how leading is distributed over
/// and under the text. With [TextLeadingDistribution.proportional]
/// (Configuration 1), `Top Leading : Bottom Leading = Font Ascent : Font
/// Descent`, which also means the alphabetic baseline divides the line height
/// into 2 parts proportional to the font's ascent and descent. With
/// [TextLeadingDistribution.even] (Configuration 3), `Top Leading` equals
/// `Bottom Leading`, and the glyphs are roughly centered within the allotted
/// line height.
///
/// The [TextPainter.textHeightBehavior] is a property that controls leading at
/// the paragraph level. The `applyHeightToFirstAscent` property is applied
/// **after** [height] and [leadingDistribution]. Setting it to false trims the
/// "Top Leading" of the text box to match the font's ascent if it's on the
/// first line (see Configuration 2). Similarly setting
/// `applyHeightToLastDescent` to false reduces "Bottom Leading" to 0 for the
/// last line of text (Configuration 4).
///
194
/// ### Wavy red underline with black text
195
///
196
/// {@tool snippet}
197 198 199 200 201
/// Styles can be combined. In this example, the misspelled word is drawn in
/// black text and underlined with a wavy red line to indicate a spelling error.
/// (The remainder is styled according to the Flutter default text styles, not
/// the ambient [DefaultTextStyle], since no explicit style is given and
/// [RichText] does not automatically use the ambient [DefaultTextStyle].)
202
///
203
/// ![](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_wavy_red_underline.png)
204
///
205
/// ```dart
206
/// RichText(
207
///   text: const TextSpan(
208
///     text: "Don't tax the South ",
209
///     children: <TextSpan>[
210
///       TextSpan(
211
///         text: 'cuz',
212
///         style: TextStyle(
213 214 215 216 217 218
///           color: Colors.black,
///           decoration: TextDecoration.underline,
///           decorationColor: Colors.red,
///           decorationStyle: TextDecorationStyle.wavy,
///         ),
///       ),
219
///       TextSpan(
220 221 222 223 224 225
///         text: ' we got it made in the shade',
///       ),
///     ],
///   ),
/// )
/// ```
226
/// {@end-tool}
227
///
228
/// ### Borders and stroke (Foreground)
229
///
230
/// {@tool snippet}
231 232 233 234
/// To create bordered text, a [Paint] with [Paint.style] set to [PaintingStyle.stroke]
/// should be provided as a [foreground] paint. The following example uses a [Stack]
/// to produce a stroke and fill effect.
///
235
/// ![](https://flutter.github.io/assets-for-api-docs/assets/widgets/text_border.png)
236 237 238 239 240 241 242 243 244 245 246 247
///
/// ```dart
/// Stack(
///   children: <Widget>[
///     // Stroked text as border.
///     Text(
///       'Greetings, planet!',
///       style: TextStyle(
///         fontSize: 40,
///         foreground: Paint()
///           ..style = PaintingStyle.stroke
///           ..strokeWidth = 6
248
///           ..color = Colors.blue[700]!,
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
///       ),
///     ),
///     // Solid text as fill.
///     Text(
///       'Greetings, planet!',
///       style: TextStyle(
///         fontSize: 40,
///         color: Colors.grey[300],
///       ),
///     ),
///   ],
/// )
/// ```
/// {@end-tool}
///
264
/// ### Gradients (Foreground)
265
///
266
/// {@tool snippet}
267 268 269 270
/// The [foreground] property also allows effects such as gradients to be
/// applied to the text. Here we provide a [Paint] with a [ui.Gradient]
/// shader.
///
271
/// ![](https://flutter.github.io/assets-for-api-docs/assets/widgets/text_gradient.png)
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
///
/// ```dart
/// Text(
///   'Greetings, planet!',
///   style: TextStyle(
///     fontSize: 40,
///     foreground: Paint()
///       ..shader = ui.Gradient.linear(
///         const Offset(0, 20),
///         const Offset(150, 20),
///         <Color>[
///           Colors.red,
///           Colors.yellow,
///         ],
///       )
///   ),
/// )
/// ```
/// {@end-tool}
///
292
/// ### Custom Fonts
293 294 295
///
/// Custom fonts can be declared in the `pubspec.yaml` file as shown below:
///
296
/// ```yaml
297 298 299 300 301 302 303 304 305 306 307 308 309 310
/// flutter:
///   fonts:
///     - family: Raleway
///       fonts:
///         - asset: fonts/Raleway-Regular.ttf
///         - asset: fonts/Raleway-Medium.ttf
///           weight: 500
///         - asset: assets/fonts/Raleway-SemiBold.ttf
///           weight: 600
///      - family: Schyler
///        fonts:
///          - asset: fonts/Schyler-Regular.ttf
///          - asset: fonts/Schyler-Italic.ttf
///            style: italic
311
/// ```
312 313 314
///
/// The `family` property determines the name of the font, which you can use in
/// the [fontFamily] argument. The `asset` property is a path to the font file,
315
/// relative to the `pubspec.yaml` file. The `weight` property specifies the
316 317
/// weight of the glyph outlines in the file as an integer multiple of 100
/// between 100 and 900. This corresponds to the [FontWeight] class and can be
318
/// used in the [fontWeight] argument. The `style` property specifies whether the
319 320 321 322 323 324
/// outlines in the file are `italic` or `normal`. These values correspond to
/// the [FontStyle] class and can be used in the [fontStyle] argument.
///
/// To select a custom font, create [TextStyle] using the [fontFamily]
/// argument as shown in the example below:
///
325
/// {@tool snippet}
326
/// ![](https://flutter.github.io/assets-for-api-docs/assets/painting/text_style_custom_fonts.png)
327
///
328 329 330
/// ```dart
/// const TextStyle(fontFamily: 'Raleway')
/// ```
331
/// {@end-tool}
332
///
333
/// To use a font family defined in a package, the `package` argument must be
334 335 336 337 338 339 340 341
/// provided. For instance, suppose the font declaration above is in the
/// `pubspec.yaml` of a package named `my_package` which the app depends on.
/// Then creating the TextStyle is done as follows:
///
/// ```dart
/// const TextStyle(fontFamily: 'Raleway', package: 'my_package')
/// ```
///
342 343
/// If the package internally uses the font it defines, it should still specify
/// the `package` argument when creating the text style as in the example above.
344
///
345 346 347 348
/// A package can also provide font files without declaring a font in its
/// `pubspec.yaml`. These files should then be in the `lib/` folder of the
/// package. The font files will not automatically be bundled in the app, instead
/// the app can use these selectively when declaring a font. Suppose a package
349
/// named `my_package` has:
350 351 352 353 354 355 356
///
/// ```
/// lib/fonts/Raleway-Medium.ttf
/// ```
///
/// Then the app can declare a font like in the example below:
///
357
/// ```yaml
358 359 360 361 362 363 364
/// flutter:
///   fonts:
///     - family: Raleway
///       fonts:
///         - asset: assets/fonts/Raleway-Regular.ttf
///         - asset: packages/my_package/fonts/Raleway-Medium.ttf
///           weight: 500
365
/// ```
366 367 368
///
/// The `lib/` is implied, so it should not be included in the asset path.
///
369
/// In this case, since the app locally defines the font, the TextStyle is
370 371
/// created without the `package` argument:
///
372
/// {@tool snippet}
373
/// ```dart
374 375
/// const TextStyle(fontFamily: 'Raleway')
/// ```
376 377
/// {@end-tool}
///
378 379
/// #### Supported font formats
///
380
/// Font formats currently supported by Flutter:
381 382 383 384 385 386 387
///
///  * `.ttc`
///  * `.ttf`
///  * `.otf`
///
/// Flutter does not support `.woff` and `.woff2` fonts for all platforms.
///
388 389 390 391 392 393 394 395 396 397 398 399
/// ### Custom Font Fallback
///
/// A custom [fontFamilyFallback] list can be provided. The list should be an
/// ordered list of strings of font family names in the order they will be attempted.
///
/// The fonts in [fontFamilyFallback] will be used only if the requested glyph is
/// not present in the [fontFamily].
///
/// The fallback order is:
///
///  * [fontFamily]
///  * [fontFamilyFallback] in order of first to last.
400
///  * System fallback fonts which will vary depending on platform.
401 402 403 404 405 406 407
///
/// The glyph used will always be the first matching version in fallback order.
///
/// The [fontFamilyFallback] property is commonly used to specify different font
/// families for multilingual text spans as well as separate fonts for glyphs such
/// as emojis.
///
408
/// {@tool snippet}
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
/// In the following example, any glyphs not present in the font `Raleway` will be attempted
/// to be resolved with `Noto Sans CJK SC`, and then with `Noto Color Emoji`:
///
/// ```dart
/// const TextStyle(
///   fontFamily: 'Raleway',
///   fontFamilyFallback: <String>[
///     'Noto Sans CJK SC',
///     'Noto Color Emoji',
///   ],
/// )
/// ```
/// {@end-tool}
///
/// If all custom fallback font families are exhausted and no match was found
/// or no custom fallback was provided, the platform font fallback will be used.
425
///
426 427
/// ### Inconsistent platform fonts
///
428 429 430 431 432 433 434 435 436 437
/// By default, fonts differ depending on the platform.
///
///  * The default font-family for `Android`,`Fuchsia` and `Linux` is `Roboto`.
///  * The default font-family for `iOS` is `.SF UI Display`/`.SF UI Text`.
///  * The default font-family for `MacOS` is `.AppleSystemUIFont`.
///  * The default font-family for `Windows` is `Segoe UI`.
//
// The implementation of these defaults can be found in:
// /packages/flutter/lib/src/material/typography.dart
///
438 439 440 441 442 443 444 445 446 447 448 449
/// Since Flutter's font discovery for default fonts depends on the fonts present
/// on the device, it is not safe to assume all default fonts will be available or
/// consistent across devices.
///
/// A known example of this is that Samsung devices ship with a CJK font that has
/// smaller line spacing than the Android default. This results in Samsung devices
/// displaying more tightly spaced text than on other Android devices when no
/// custom font is specified.
///
/// To avoid this, a custom font should be specified if absolute font consistency
/// is required for your application.
///
450 451
/// See also:
///
452
///  * [Text], the widget for showing text in a single style.
453 454
///  * [DefaultTextStyle], the widget that specifies the default text styles for
///    [Text] widgets, configured using a [TextStyle].
455
///  * [RichText], the widget for showing a paragraph of mix-style text.
456
///  * [TextSpan], the class that wraps a [TextStyle] for the purposes of
457 458
///    passing it to a [RichText].
///  * [TextStyle](https://api.flutter.dev/flutter/dart-ui/TextStyle-class.html), the class in the [dart:ui] library.
459 460
///  * Cookbook: [Use a custom font](https://flutter.dev/docs/cookbook/design/fonts)
///  * Cookbook: [Use themes to share colors and font styles](https://flutter.dev/docs/cookbook/design/themes)
461
@immutable
462
class TextStyle with Diagnosticable {
463
  /// Creates a text style.
464 465 466 467
  ///
  /// The `package` argument must be non-null if the font family is defined in a
  /// package. It is combined with the `fontFamily` argument to set the
  /// [fontFamily] property.
468
  const TextStyle({
469
    this.inherit = true,
470
    this.color,
471
    this.backgroundColor,
472 473
    this.fontSize,
    this.fontWeight,
474
    this.fontStyle,
475
    this.letterSpacing,
476
    this.wordSpacing,
477
    this.textBaseline,
478
    this.height,
479
    this.leadingDistribution,
480
    this.locale,
481
    this.foreground,
482
    this.background,
483
    this.shadows,
484
    this.fontFeatures,
485
    this.fontVariations,
486 487
    this.decoration,
    this.decorationColor,
488
    this.decorationStyle,
489
    this.decorationThickness,
490
    this.debugLabel,
491 492 493
    String? fontFamily,
    List<String>? fontFamilyFallback,
    String? package,
494
    this.overflow,
495
  }) : fontFamily = package == null ? fontFamily : 'packages/$package/$fontFamily',
496 497
       _fontFamilyFallback = fontFamilyFallback,
       _package = package,
498
       assert(inherit != null),
499 500
       assert(color == null || foreground == null, _kColorForegroundWarning),
       assert(backgroundColor == null || background == null, _kColorBackgroundWarning);
501

502

503 504 505 506
  /// Whether null values are replaced with their value in an ancestor text
  /// style (e.g., in a [TextSpan] tree).
  ///
  /// If this is false, properties that don't have explicit values will revert
507
  /// to the defaults: white in color, a font size of 14 pixels, in a sans-serif
508
  /// font face.
509 510
  final bool inherit;

511
  /// The color to use when painting the text.
512
  ///
513
  /// If [foreground] is specified, this value must be null. The [color] property
514
  /// is shorthand for `Paint()..color = color`.
515
  ///
516 517 518
  /// In [merge], [apply], and [lerp], conflicts between [color] and [foreground]
  /// specification are resolved in [foreground]'s favor - i.e. if [foreground] is
  /// specified in one place, it will dominate [color] in another.
519
  final Color? color;
520

521 522 523 524 525 526 527 528 529
  /// The color to use as the background for the text.
  ///
  /// If [background] is specified, this value must be null. The
  /// [backgroundColor] property is shorthand for
  /// `background: Paint()..color = backgroundColor`.
  ///
  /// In [merge], [apply], and [lerp], conflicts between [backgroundColor] and [background]
  /// specification are resolved in [background]'s favor - i.e. if [background] is
  /// specified in one place, it will dominate [color] in another.
530
  final Color? backgroundColor;
531

532 533 534
  /// The name of the font to use when painting the text (e.g., Roboto).
  ///
  /// If the font is defined in a package, this will be prefixed with
535 536 537
  /// 'packages/package_name/' (e.g. 'packages/cool_fonts/Roboto'). The
  /// prefixing is done by the constructor when the `package` argument is
  /// provided.
538 539 540 541 542 543 544
  ///
  /// The value provided in [fontFamily] will act as the preferred/first font
  /// family that glyphs are looked for in, followed in order by the font families
  /// in [fontFamilyFallback]. When [fontFamily] is null or not provided, the
  /// first value in [fontFamilyFallback] acts as the preferred/first font
  /// family. When neither is provided, then the default platform font will
  /// be used.
545
  final String? fontFamily;
546

547 548 549 550 551 552 553 554 555 556
  /// The ordered list of font families to fall back on when a glyph cannot be
  /// found in a higher priority font family.
  ///
  /// The value provided in [fontFamily] will act as the preferred/first font
  /// family that glyphs are looked for in, followed in order by the font families
  /// in [fontFamilyFallback]. If all font families are exhausted and no match
  /// was found, the default platform font family will be used instead.
  ///
  /// When [fontFamily] is null or not provided, the first value in [fontFamilyFallback]
  /// acts as the preferred/first font family. When neither is provided, then
557
  /// the default platform font will be used. Providing an empty list or null
558 559 560 561 562 563 564 565 566 567
  /// for this property is the same as omitting it.
  ///
  /// For example, if a glyph is not found in [fontFamily], then each font family
  /// in [fontFamilyFallback] will be searched in order until it is found. If it
  /// is not found, then a box will be drawn in its place.
  ///
  /// If the font is defined in a package, each font family in the list will be
  /// prefixed with 'packages/package_name/' (e.g. 'packages/cool_fonts/Roboto').
  /// The package name should be provided by the `package` argument in the
  /// constructor.
568 569
  List<String>? get fontFamilyFallback => _package != null && _fontFamilyFallback != null ? _fontFamilyFallback!.map((String str) => 'packages/$_package/$str').toList() : _fontFamilyFallback;
  final List<String>? _fontFamilyFallback;
570 571 572

  // This is stored in order to prefix the fontFamilies in _fontFamilyFallback
  // in the [fontFamilyFallback] getter.
573
  final String? _package;
574

575
  /// The size of glyphs (in logical pixels) to use when painting the text.
576 577 578 579
  ///
  /// During painting, the [fontSize] is multiplied by the current
  /// `textScaleFactor` to let users make it easier to read text by increasing
  /// its size.
580 581 582
  ///
  /// [getParagraphStyle] will default to 14 logical pixels if the font size
  /// isn't specified here.
583
  final double? fontSize;
584

585
  /// The typeface thickness to use when painting the text (e.g., bold).
586
  final FontWeight? fontWeight;
587

588
  /// The typeface variant to use when drawing the letters (e.g., italics).
589
  final FontStyle? fontStyle;
590

591
  /// The amount of space (in logical pixels) to add between each letter.
xster's avatar
xster committed
592
  /// A negative value can be used to bring the letters closer.
593
  final double? letterSpacing;
594

595 596 597
  /// The amount of space (in logical pixels) to add at each sequence of
  /// white-space (i.e. between each word). A negative value can be used to
  /// bring the words closer.
598
  final double? wordSpacing;
599

600 601
  /// The common baseline that should be aligned between this text span and its
  /// parent text span, or, for the root text spans, with the line box.
602
  final TextBaseline? textBaseline;
603

604 605
  /// The height of this text span, as a multiple of the font size.
  ///
606 607 608 609 610 611 612 613 614 615 616 617 618
  /// When [height] is null or omitted, the line height will be determined
  /// by the font's metrics directly, which may differ from the fontSize.
  /// When [height] is non-null, the line height of the span of text will be a
  /// multiple of [fontSize] and be exactly `fontSize * height` logical pixels
  /// tall.
  ///
  /// For most fonts, setting [height] to 1.0 is not the same as omitting or
  /// setting height to null because the [fontSize] sets the height of the EM-square,
  /// which is different than the font provided metrics for line height. The
  /// following diagram illustrates the difference between the font-metrics
  /// defined line height and the line height produced with `height: 1.0`
  /// (which forms the upper and lower edges of the EM-square):
  ///
619
  /// ![With the font-metrics-defined line height, there is space between lines appropriate for the font, whereas the EM-square is only the height required to hold most of the characters.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_height_diagram.png)
620 621 622
  ///
  /// Examples of the resulting line heights from different values of `TextStyle.height`:
  ///
623
  /// ![Since the explicit line height is applied as a scale factor on the font-metrics-defined line height, the gap above the text grows faster, as the height grows, than the gap below the text.](https://flutter.github.io/assets-for-api-docs/assets/painting/text_height_comparison_diagram.png)
624
  ///
625 626
  /// See [StrutStyle] and [TextHeightBehavior] for further control of line
  /// height at the paragraph level.
627
  final double? height;
628

629 630 631 632 633 634
  /// How the vertical space added by the [height] multiplier should be
  /// distributed over and under the text.
  ///
  /// When a non-null [height] is specified, after accommodating the glyphs of
  /// the text, the remaining vertical space from the allotted line height will
  /// be distributed over and under the text, according to the
635 636
  /// [leadingDistribution] property. See the [TextStyle] class's documentation
  /// for an example.
637 638 639 640 641 642 643 644
  ///
  /// When [height] is null, [leadingDistribution] does not affect the text
  /// layout.
  ///
  /// Defaults to null, which defers to the paragraph's
  /// `ParagraphStyle.textHeightBehavior`'s `leadingDistribution`.
  final ui.TextLeadingDistribution? leadingDistribution;

645
  /// The locale used to select region-specific glyphs.
646 647 648 649
  ///
  /// This property is rarely set. Typically the locale used to select
  /// region-specific glyphs is defined by the text widget's [BuildContext]
  /// using `Localizations.localeOf(context)`. For example [RichText] defines
650 651 652
  /// its locale this way. However, a rich text widget's [TextSpan]s could
  /// specify text styles with different explicit locales in order to select
  /// different region-specific glyphs for each text span.
653
  final Locale? locale;
654

655 656 657 658 659 660
  /// The paint drawn as a foreground for the text.
  ///
  /// The value should ideally be cached and reused each time if multiple text
  /// styles are created with the same paint settings. Otherwise, each time it
  /// will appear like the style changed, which will result in unnecessary
  /// updates all the way through the framework.
661
  ///
662
  /// If [color] is specified, this value must be null. The [color] property
663
  /// is shorthand for `Paint()..color = color`.
664
  ///
665 666 667
  /// In [merge], [apply], and [lerp], conflicts between [color] and [foreground]
  /// specification are resolved in [foreground]'s favor - i.e. if [foreground] is
  /// specified in one place, it will dominate [color] in another.
668
  final Paint? foreground;
669

670 671 672 673 674 675
  /// The paint drawn as a background for the text.
  ///
  /// The value should ideally be cached and reused each time if multiple text
  /// styles are created with the same paint settings. Otherwise, each time it
  /// will appear like the style changed, which will result in unnecessary
  /// updates all the way through the framework.
676 677 678 679 680 681 682 683 684
  ///
  /// If [backgroundColor] is specified, this value must be null. The
  /// [backgroundColor] property is shorthand for
  /// `background: Paint()..color = backgroundColor`.
  ///
  /// In [merge], [apply], and [lerp], conflicts between [backgroundColor] and
  /// [background] specification are resolved in [background]'s favor - i.e. if
  /// [background] is specified in one place, it will dominate [backgroundColor]
  /// in another.
685
  final Paint? background;
686

687
  /// The decorations to paint near the text (e.g., an underline).
688 689
  ///
  /// Multiple decorations can be applied using [TextDecoration.combine].
690
  final TextDecoration? decoration;
691

692
  /// The color in which to paint the text decorations.
693
  final Color? decorationColor;
694

695
  /// The style in which to paint the text decorations (e.g., dashed).
696
  final TextDecorationStyle? decorationStyle;
697

698
  /// The thickness of the decoration stroke as a multiplier of the thickness
699 700 701 702 703 704 705 706
  /// defined by the font.
  ///
  /// The font provides a base stroke width for [decoration]s which scales off
  /// of the [fontSize]. This property may be used to achieve a thinner or
  /// thicker decoration stroke, without changing the [fontSize]. For example,
  /// a [decorationThickness] of 2.0 will draw a decoration twice as thick as
  /// the font defined decoration thickness.
  ///
707
  /// {@tool snippet}
708 709 710 711
  /// To achieve a bolded strike-through, we can apply a thicker stroke for the
  /// decoration.
  ///
  /// ```dart
712
  /// const Text(
713 714 715 716 717 718 719 720 721
  ///   'This has a very BOLD strike through!',
  ///   style: TextStyle(
  ///     decoration: TextDecoration.lineThrough,
  ///     decorationThickness: 2.85,
  ///   ),
  /// )
  /// ```
  /// {@end-tool}
  ///
722
  /// {@tool snippet}
723 724 725 726
  /// We can apply a very thin and subtle wavy underline (perhaps, when words
  /// are misspelled) by using a [decorationThickness] < 1.0.
  ///
  /// ```dart
727
  /// const Text(
728 729 730 731 732 733 734 735 736 737 738 739 740
  ///   'oopsIforgottousespaces!',
  ///   style: TextStyle(
  ///     decoration: TextDecoration.underline,
  ///     decorationStyle: TextDecorationStyle.wavy,
  ///     decorationColor: Colors.red,
  ///     decorationThickness: 0.5,
  ///   ),
  /// )
  /// ```
  /// {@end-tool}
  ///
  /// The default [decorationThickness] is 1.0, which will use the font's base
  /// stroke thickness/width.
741
  final double? decorationThickness;
742

743 744 745 746 747 748 749 750 751 752 753
  /// A human-readable description of this text style.
  ///
  /// This property is maintained only in debug builds.
  ///
  /// When merging ([merge]), copying ([copyWith]), modifying using [apply], or
  /// interpolating ([lerp]), the label of the resulting style is marked with
  /// the debug labels of the original styles. This helps figuring out where a
  /// particular text style came from.
  ///
  /// This property is not considered when comparing text styles using `==` or
  /// [compareTo], and it does not affect [hashCode].
754
  final String? debugLabel;
755

756 757 758 759 760 761 762
  /// A list of [Shadow]s that will be painted underneath the text.
  ///
  /// Multiple shadows are supported to replicate lighting from multiple light
  /// sources.
  ///
  /// Shadows must be in the same order for [TextStyle] to be considered as
  /// equivalent as order produces differing transparency.
763
  final List<ui.Shadow>? shadows;
764

765 766 767 768 769 770 771
  /// A list of [FontFeature]s that affect how the font selects glyphs.
  ///
  /// Some fonts support multiple variants of how a given character can be
  /// rendered.  For example, a font might provide both proportional and
  /// tabular numbers, or it might offer versions of the zero digit with
  /// and without slashes.  [FontFeature]s can be used to select which of
  /// these variants will be used for rendering.
772
  final List<ui.FontFeature>? fontFeatures;
773

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  /// A list of [FontVariation]s that affect how a variable font is rendered.
  ///
  /// Some fonts are variable fonts that can generate multiple font faces based
  /// on the values of customizable attributes.  For example, a variable font
  /// may have a weight axis that can be set to a value between 1 and 1000.
  /// [FontVariation]s can be used to select the values of these design axes.
  ///
  /// For example, to control the weight axis of the Roboto Slab variable font
  /// (https://fonts.google.com/specimen/Roboto+Slab):
  /// ```dart
  /// TextStyle(
  ///   fontFamily: 'RobotoSlab',
  ///   fontVariations: <FontVariation>[FontVariation('wght', 900.0)]
  /// )
  /// ```
  final List<ui.FontVariation>? fontVariations;

791 792 793
  /// How visual text overflow should be handled.
  final TextOverflow? overflow;

794 795 796 797 798 799 800 801 802 803 804
  // Return the original value of fontFamily, without the additional
  // "packages/$_package/" prefix.
  String? get _fontFamily {
    if (_package != null && fontFamily != null) {
      final String fontFamilyPrefix = 'packages/$_package/';
      assert(fontFamily!.startsWith(fontFamilyPrefix));
      return fontFamily!.substring(fontFamilyPrefix.length);
    }
    return fontFamily;
  }

805 806
  /// Creates a copy of this text style but with the given fields replaced with
  /// the new values.
807
  ///
808 809
  /// One of [color] or [foreground] must be null, and if this has [foreground]
  /// specified it will be given preference over any color parameter.
810 811 812 813
  ///
  /// One of [backgroundColor] or [background] must be null, and if this has
  /// [background] specified it will be given preference over any
  /// backgroundColor parameter.
814
  TextStyle copyWith({
815 816 817 818 819 820 821 822 823 824
    bool? inherit,
    Color? color,
    Color? backgroundColor,
    double? fontSize,
    FontWeight? fontWeight,
    FontStyle? fontStyle,
    double? letterSpacing,
    double? wordSpacing,
    TextBaseline? textBaseline,
    double? height,
825
    ui.TextLeadingDistribution? leadingDistribution,
826 827 828 829 830
    Locale? locale,
    Paint? foreground,
    Paint? background,
    List<ui.Shadow>? shadows,
    List<ui.FontFeature>? fontFeatures,
831
    List<ui.FontVariation>? fontVariations,
832 833 834 835 836
    TextDecoration? decoration,
    Color? decorationColor,
    TextDecorationStyle? decorationStyle,
    double? decorationThickness,
    String? debugLabel,
837 838 839
    String? fontFamily,
    List<String>? fontFamilyFallback,
    String? package,
840
    TextOverflow? overflow,
841
  }) {
842
    assert(color == null || foreground == null, _kColorForegroundWarning);
843
    assert(backgroundColor == null || background == null, _kColorBackgroundWarning);
844
    String? newDebugLabel;
845
    assert(() {
846
      if (this.debugLabel != null) {
847
        newDebugLabel = debugLabel ?? '(${this.debugLabel}).copyWith';
848
      }
849 850
      return true;
    }());
851

852
    return TextStyle(
853
      inherit: inherit ?? this.inherit,
854
      color: this.foreground == null && foreground == null ? color ?? this.color : null,
855
      backgroundColor: this.background == null && background == null ? backgroundColor ?? this.backgroundColor : null,
Ian Hickson's avatar
Ian Hickson committed
856 857 858 859 860 861 862
      fontSize: fontSize ?? this.fontSize,
      fontWeight: fontWeight ?? this.fontWeight,
      fontStyle: fontStyle ?? this.fontStyle,
      letterSpacing: letterSpacing ?? this.letterSpacing,
      wordSpacing: wordSpacing ?? this.wordSpacing,
      textBaseline: textBaseline ?? this.textBaseline,
      height: height ?? this.height,
863
      leadingDistribution: leadingDistribution ?? this.leadingDistribution,
864
      locale: locale ?? this.locale,
865
      foreground: foreground ?? this.foreground,
866
      background: background ?? this.background,
867
      shadows: shadows ?? this.shadows,
868
      fontFeatures: fontFeatures ?? this.fontFeatures,
869
      fontVariations: fontVariations ?? this.fontVariations,
Ian Hickson's avatar
Ian Hickson committed
870 871
      decoration: decoration ?? this.decoration,
      decorationColor: decorationColor ?? this.decorationColor,
872
      decorationStyle: decorationStyle ?? this.decorationStyle,
873
      decorationThickness: decorationThickness ?? this.decorationThickness,
874
      debugLabel: newDebugLabel,
875 876 877
      fontFamily: fontFamily ?? _fontFamily,
      fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,
      package: package ?? _package,
878
      overflow: overflow ?? this.overflow,
879 880 881
    );
  }

882 883 884 885 886
  /// Creates a copy of this text style replacing or altering the specified
  /// properties.
  ///
  /// The non-numeric properties [color], [fontFamily], [decoration],
  /// [decorationColor] and [decorationStyle] are replaced with the new values.
887
  ///
888 889 890
  /// [foreground] will be given preference over [color] if it is not null and
  /// [background] will be given preference over [backgroundColor] if it is not
  /// null.
891 892 893
  ///
  /// The numeric properties are multiplied by the given factors and then
  /// incremented by the given deltas.
Ian Hickson's avatar
Ian Hickson committed
894
  ///
895 896
  /// For example, `style.apply(fontSizeFactor: 2.0, fontSizeDelta: 1.0)` would
  /// return a [TextStyle] whose [fontSize] is `style.fontSize * 2.0 + 1.0`.
Ian Hickson's avatar
Ian Hickson committed
897 898 899 900 901 902
  ///
  /// For the [fontWeight], the delta is applied to the [FontWeight] enum index
  /// values, so that for instance `style.apply(fontWeightDelta: -2)` when
  /// applied to a `style` whose [fontWeight] is [FontWeight.w500] will return a
  /// [TextStyle] with a [FontWeight.w300].
  ///
903
  /// The numeric arguments must not be null.
Ian Hickson's avatar
Ian Hickson committed
904 905 906
  ///
  /// If the underlying values are null, then the corresponding factors and/or
  /// deltas must not be specified.
907
  ///
908
  /// If [foreground] is specified on this object, then applying [color] here
909 910
  /// will have no effect and if [background] is specified on this object, then
  /// applying [backgroundColor] here will have no effect either.
Ian Hickson's avatar
Ian Hickson committed
911
  TextStyle apply({
912 913 914 915 916
    Color? color,
    Color? backgroundColor,
    TextDecoration? decoration,
    Color? decorationColor,
    TextDecorationStyle? decorationStyle,
917 918
    double decorationThicknessFactor = 1.0,
    double decorationThicknessDelta = 0.0,
919 920
    String? fontFamily,
    List<String>? fontFamilyFallback,
921 922 923
    double fontSizeFactor = 1.0,
    double fontSizeDelta = 0.0,
    int fontWeightDelta = 0,
924
    FontStyle? fontStyle,
925 926 927 928 929 930
    double letterSpacingFactor = 1.0,
    double letterSpacingDelta = 0.0,
    double wordSpacingFactor = 1.0,
    double wordSpacingDelta = 0.0,
    double heightFactor = 1.0,
    double heightDelta = 0.0,
931
    TextBaseline? textBaseline,
932
    ui.TextLeadingDistribution? leadingDistribution,
933 934 935
    Locale? locale,
    List<ui.Shadow>? shadows,
    List<ui.FontFeature>? fontFeatures,
936
    List<ui.FontVariation>? fontVariations,
937
    String? package,
938
    TextOverflow? overflow,
Ian Hickson's avatar
Ian Hickson committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952
  }) {
    assert(fontSizeFactor != null);
    assert(fontSizeDelta != null);
    assert(fontSize != null || (fontSizeFactor == 1.0 && fontSizeDelta == 0.0));
    assert(fontWeightDelta != null);
    assert(fontWeight != null || fontWeightDelta == 0.0);
    assert(letterSpacingFactor != null);
    assert(letterSpacingDelta != null);
    assert(letterSpacing != null || (letterSpacingFactor == 1.0 && letterSpacingDelta == 0.0));
    assert(wordSpacingFactor != null);
    assert(wordSpacingDelta != null);
    assert(wordSpacing != null || (wordSpacingFactor == 1.0 && wordSpacingDelta == 0.0));
    assert(heightFactor != null);
    assert(heightDelta != null);
953 954 955
    assert(decorationThicknessFactor != null);
    assert(decorationThicknessDelta != null);
    assert(decorationThickness != null || (decorationThicknessFactor == 1.0 && decorationThicknessDelta == 0.0));
956

957
    String? modifiedDebugLabel;
958
    assert(() {
959
      if (debugLabel != null) {
960
        modifiedDebugLabel = '($debugLabel).apply';
961
      }
962 963 964
      return true;
    }());

965
    return TextStyle(
Ian Hickson's avatar
Ian Hickson committed
966
      inherit: inherit,
967
      color: foreground == null ? color ?? this.color : null,
968
      backgroundColor: background == null ? backgroundColor ?? this.backgroundColor : null,
969
      fontFamily: fontFamily ?? _fontFamily,
970
      fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,
971
      fontSize: fontSize == null ? null : fontSize! * fontSizeFactor + fontSizeDelta,
972
      fontWeight: fontWeight == null ? null : FontWeight.values[(fontWeight!.index + fontWeightDelta).clamp(0, FontWeight.values.length - 1)], // ignore_clamp_double_lint
973
      fontStyle: fontStyle ?? this.fontStyle,
974 975
      letterSpacing: letterSpacing == null ? null : letterSpacing! * letterSpacingFactor + letterSpacingDelta,
      wordSpacing: wordSpacing == null ? null : wordSpacing! * wordSpacingFactor + wordSpacingDelta,
976
      textBaseline: textBaseline ?? this.textBaseline,
977
      height: height == null ? null : height! * heightFactor + heightDelta,
978
      leadingDistribution: leadingDistribution ?? this.leadingDistribution,
979
      locale: locale ?? this.locale,
980
      foreground: foreground,
981
      background: background,
982 983
      shadows: shadows ?? this.shadows,
      fontFeatures: fontFeatures ?? this.fontFeatures,
984
      fontVariations: fontVariations ?? this.fontVariations,
985 986 987
      decoration: decoration ?? this.decoration,
      decorationColor: decorationColor ?? this.decorationColor,
      decorationStyle: decorationStyle ?? this.decorationStyle,
988
      decorationThickness: decorationThickness == null ? null : decorationThickness! * decorationThicknessFactor + decorationThicknessDelta,
989
      overflow: overflow ?? this.overflow,
990
      package: package ?? _package,
991
      debugLabel: modifiedDebugLabel,
Ian Hickson's avatar
Ian Hickson committed
992 993 994
    );
  }

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  /// Returns a new text style that is a combination of this style and the given
  /// [other] style.
  ///
  /// If the given [other] text style has its [TextStyle.inherit] set to true,
  /// its null properties are replaced with the non-null properties of this text
  /// style. The [other] style _inherits_ the properties of this style. Another
  /// way to think of it is that the "missing" properties of the [other] style
  /// are _filled_ by the properties of this style.
  ///
  /// If the given [other] text style has its [TextStyle.inherit] set to false,
  /// returns the given [other] style unchanged. The [other] style does not
  /// inherit properties of this style.
  ///
  /// If the given text style is null, returns this text style.
1009
  ///
1010 1011
  /// One of [color] or [foreground] must be null, and if this or `other` has
  /// [foreground] specified it will be given preference over any color parameter.
1012
  ///
1013
  /// Similarly, one of [backgroundColor] or [background] must be null, and if
1014 1015
  /// this or `other` has [background] specified it will be given preference
  /// over any backgroundColor parameter.
1016
  TextStyle merge(TextStyle? other) {
1017
    if (other == null) {
1018
      return this;
1019 1020
    }
    if (!other.inherit) {
1021
      return other;
1022
    }
1023

1024
    String? mergedDebugLabel;
1025
    assert(() {
1026
      if (other.debugLabel != null || debugLabel != null) {
1027
        mergedDebugLabel = '(${debugLabel ?? _kDefaultDebugLabel}).merge(${other.debugLabel ?? _kDefaultDebugLabel})';
1028
      }
1029 1030 1031
      return true;
    }());

1032 1033
    return copyWith(
      color: other.color,
1034
      backgroundColor: other.backgroundColor,
1035 1036
      fontSize: other.fontSize,
      fontWeight: other.fontWeight,
1037
      fontStyle: other.fontStyle,
1038
      letterSpacing: other.letterSpacing,
1039
      wordSpacing: other.wordSpacing,
1040
      textBaseline: other.textBaseline,
1041
      height: other.height,
1042
      leadingDistribution: other.leadingDistribution,
1043
      locale: other.locale,
1044
      foreground: other.foreground,
1045
      background: other.background,
1046
      shadows: other.shadows,
1047
      fontFeatures: other.fontFeatures,
1048
      fontVariations: other.fontVariations,
1049 1050
      decoration: other.decoration,
      decorationColor: other.decorationColor,
1051
      decorationStyle: other.decorationStyle,
1052
      decorationThickness: other.decorationThickness,
1053
      debugLabel: mergedDebugLabel,
1054 1055 1056 1057
      fontFamily: other._fontFamily,
      fontFamilyFallback: other.fontFamilyFallback,
      package: other._package,
      overflow: other.overflow,
1058 1059 1060
    );
  }

1061 1062 1063
  /// Interpolate between two text styles.
  ///
  /// This will not work well if the styles don't set the same fields.
1064
  ///
1065
  /// {@macro dart.ui.shadow.lerp}
1066
  ///
1067 1068 1069
  /// If [foreground] is specified on either of `a` or `b`, both will be treated
  /// as if they have a [foreground] paint (creating a new [Paint] if necessary
  /// based on the [color] property).
1070 1071 1072 1073
  ///
  /// If [background] is specified on either of `a` or `b`, both will be treated
  /// as if they have a [background] paint (creating a new [Paint] if necessary
  /// based on the [backgroundColor] property).
1074
  static TextStyle? lerp(TextStyle? a, TextStyle? b, double t) {
1075
    assert(t != null);
1076 1077 1078 1079
    assert(a == null || b == null || a.inherit == b.inherit);
    if (a == null && b == null) {
      return null;
    }
1080

1081
    String? lerpDebugLabel;
1082
    assert(() {
1083
      lerpDebugLabel = 'lerp(${a?.debugLabel ?? _kDefaultDebugLabel}${t.toStringAsFixed(1)}${b?.debugLabel ?? _kDefaultDebugLabel})';
1084 1085 1086
      return true;
    }());

1087
    if (a == null) {
1088
      return TextStyle(
1089
        inherit: b!.inherit,
1090
        color: Color.lerp(null, b.color, t),
1091
        backgroundColor: Color.lerp(null, b.backgroundColor, t),
1092 1093 1094 1095 1096 1097 1098
        fontSize: t < 0.5 ? null : b.fontSize,
        fontWeight: FontWeight.lerp(null, b.fontWeight, t),
        fontStyle: t < 0.5 ? null : b.fontStyle,
        letterSpacing: t < 0.5 ? null : b.letterSpacing,
        wordSpacing: t < 0.5 ? null : b.wordSpacing,
        textBaseline: t < 0.5 ? null : b.textBaseline,
        height: t < 0.5 ? null : b.height,
1099
        leadingDistribution: t < 0.5 ? null : b.leadingDistribution,
1100
        locale: t < 0.5 ? null : b.locale,
1101
        foreground: t < 0.5 ? null : b.foreground,
1102
        background: t < 0.5 ? null : b.background,
1103
        shadows: t < 0.5 ? null : b.shadows,
1104
        fontFeatures: t < 0.5 ? null : b.fontFeatures,
1105
        fontVariations: t < 0.5 ? null : b.fontVariations,
1106
        decoration: t < 0.5 ? null : b.decoration,
1107 1108
        decorationColor: Color.lerp(null, b.decorationColor, t),
        decorationStyle: t < 0.5 ? null : b.decorationStyle,
1109
        decorationThickness: t < 0.5 ? null : b.decorationThickness,
1110
        debugLabel: lerpDebugLabel,
1111 1112 1113 1114
        fontFamily: t < 0.5 ? null : b._fontFamily,
        fontFamilyFallback: t < 0.5 ? null : b.fontFamilyFallback,
        package: t < 0.5 ? null : b._package,
        overflow: t < 0.5 ? null : b.overflow,
1115 1116 1117 1118
      );
    }

    if (b == null) {
1119
      return TextStyle(
1120 1121
        inherit: a.inherit,
        color: Color.lerp(a.color, null, t),
1122
        backgroundColor: Color.lerp(null, a.backgroundColor, t),
1123 1124 1125 1126 1127 1128 1129
        fontSize: t < 0.5 ? a.fontSize : null,
        fontWeight: FontWeight.lerp(a.fontWeight, null, t),
        fontStyle: t < 0.5 ? a.fontStyle : null,
        letterSpacing: t < 0.5 ? a.letterSpacing : null,
        wordSpacing: t < 0.5 ? a.wordSpacing : null,
        textBaseline: t < 0.5 ? a.textBaseline : null,
        height: t < 0.5 ? a.height : null,
1130
        leadingDistribution: t < 0.5 ? a.leadingDistribution : null,
1131
        locale: t < 0.5 ? a.locale : null,
1132
        foreground: t < 0.5 ? a.foreground : null,
1133
        background: t < 0.5 ? a.background : null,
1134
        shadows: t < 0.5 ? a.shadows : null,
1135
        fontFeatures: t < 0.5 ? a.fontFeatures : null,
1136
        fontVariations: t < 0.5 ? a.fontVariations : null,
1137 1138 1139
        decoration: t < 0.5 ? a.decoration : null,
        decorationColor: Color.lerp(a.decorationColor, null, t),
        decorationStyle: t < 0.5 ? a.decorationStyle : null,
1140
        decorationThickness: t < 0.5 ? a.decorationThickness : null,
1141
        debugLabel: lerpDebugLabel,
1142 1143 1144 1145
        fontFamily: t < 0.5 ? a._fontFamily : null,
        fontFamilyFallback: t < 0.5 ? a.fontFamilyFallback : null,
        package: t < 0.5 ? a._package : null,
        overflow: t < 0.5 ? a.overflow : null,
1146 1147 1148
      );
    }

1149
    return TextStyle(
1150
      inherit: b.inherit,
1151
      color: a.foreground == null && b.foreground == null ? Color.lerp(a.color, b.color, t) : null,
1152
      backgroundColor: a.background == null && b.background == null ? Color.lerp(a.backgroundColor, b.backgroundColor, t) : null,
1153 1154 1155 1156 1157 1158 1159
      fontSize: ui.lerpDouble(a.fontSize ?? b.fontSize, b.fontSize ?? a.fontSize, t),
      fontWeight: FontWeight.lerp(a.fontWeight, b.fontWeight, t),
      fontStyle: t < 0.5 ? a.fontStyle : b.fontStyle,
      letterSpacing: ui.lerpDouble(a.letterSpacing ?? b.letterSpacing, b.letterSpacing ?? a.letterSpacing, t),
      wordSpacing: ui.lerpDouble(a.wordSpacing ?? b.wordSpacing, b.wordSpacing ?? a.wordSpacing, t),
      textBaseline: t < 0.5 ? a.textBaseline : b.textBaseline,
      height: ui.lerpDouble(a.height ?? b.height, b.height ?? a.height, t),
1160
      leadingDistribution: t < 0.5 ? a.leadingDistribution : b.leadingDistribution,
1161
      locale: t < 0.5 ? a.locale : b.locale,
1162
      foreground: (a.foreground != null || b.foreground != null)
1163
        ? t < 0.5
1164 1165
          ? a.foreground ?? (Paint()..color = a.color!)
          : b.foreground ?? (Paint()..color = b.color!)
1166
        : null,
1167 1168
      background: (a.background != null || b.background != null)
        ? t < 0.5
1169 1170
          ? a.background ?? (Paint()..color = a.backgroundColor!)
          : b.background ?? (Paint()..color = b.backgroundColor!)
1171
        : null,
1172
      shadows: t < 0.5 ? a.shadows : b.shadows,
1173
      fontFeatures: t < 0.5 ? a.fontFeatures : b.fontFeatures,
1174
      fontVariations: t < 0.5 ? a.fontVariations : b.fontVariations,
1175 1176 1177
      decoration: t < 0.5 ? a.decoration : b.decoration,
      decorationColor: Color.lerp(a.decorationColor, b.decorationColor, t),
      decorationStyle: t < 0.5 ? a.decorationStyle : b.decorationStyle,
1178
      decorationThickness: ui.lerpDouble(a.decorationThickness ?? b.decorationThickness, b.decorationThickness ?? a.decorationThickness, t),
1179
      debugLabel: lerpDebugLabel,
1180 1181 1182 1183
      fontFamily: t < 0.5 ? a._fontFamily : b._fontFamily,
      fontFamilyFallback: t < 0.5 ? a.fontFamilyFallback : b.fontFamilyFallback,
      package: t < 0.5 ? a._package : b._package,
      overflow: t < 0.5 ? a.overflow : b.overflow,
1184 1185
    );
  }
1186

1187
  /// The style information for text runs, encoded for use by `dart:ui`.
1188
  ui.TextStyle getTextStyle({ double textScaleFactor = 1.0 }) {
1189
    return ui.TextStyle(
1190 1191 1192 1193
      color: color,
      decoration: decoration,
      decorationColor: decorationColor,
      decorationStyle: decorationStyle,
1194
      decorationThickness: decorationThickness,
1195 1196
      fontWeight: fontWeight,
      fontStyle: fontStyle,
1197
      textBaseline: textBaseline,
1198
      leadingDistribution: leadingDistribution,
1199
      fontFamily: fontFamily,
1200
      fontFamilyFallback: fontFamilyFallback,
1201
      fontSize: fontSize == null ? null : fontSize! * textScaleFactor,
1202 1203
      letterSpacing: letterSpacing,
      wordSpacing: wordSpacing,
1204 1205
      height: height,
      locale: locale,
1206
      foreground: foreground,
1207
      background: background ?? (backgroundColor != null
1208
        ? (Paint()..color = backgroundColor!)
1209 1210
        : null
      ),
1211
      shadows: shadows,
1212
      fontFeatures: fontFeatures,
1213
      fontVariations: fontVariations,
1214 1215 1216
    );
  }

1217
  /// The style information for paragraphs, encoded for use by `dart:ui`.
1218 1219 1220 1221
  ///
  /// The `textScaleFactor` argument must not be null. If omitted, it defaults
  /// to 1.0. The other arguments may be null. The `maxLines` argument, if
  /// specified and non-null, must be greater than zero.
1222 1223 1224
  ///
  /// If the font size on this style isn't set, it will default to 14 logical
  /// pixels.
1225
  ui.ParagraphStyle getParagraphStyle({
1226 1227
    TextAlign? textAlign,
    TextDirection? textDirection,
1228
    double textScaleFactor = 1.0,
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    String? ellipsis,
    int? maxLines,
    ui.TextHeightBehavior? textHeightBehavior,
    Locale? locale,
    String? fontFamily,
    double? fontSize,
    FontWeight? fontWeight,
    FontStyle? fontStyle,
    double? height,
    StrutStyle? strutStyle,
1239 1240 1241
  }) {
    assert(textScaleFactor != null);
    assert(maxLines == null || maxLines > 0);
1242 1243 1244
    final ui.TextLeadingDistribution? leadingDistribution = this.leadingDistribution;
    final ui.TextHeightBehavior? effectiveTextHeightBehavior = textHeightBehavior
      ?? (leadingDistribution == null ? null : ui.TextHeightBehavior(leadingDistribution: leadingDistribution));
1245
    return ui.ParagraphStyle(
1246
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
1247
      textDirection: textDirection,
1248
      // Here, we establish the contents of this TextStyle as the paragraph's default font
1249 1250 1251 1252
      // unless an override is passed in.
      fontWeight: fontWeight ?? this.fontWeight,
      fontStyle: fontStyle ?? this.fontStyle,
      fontFamily: fontFamily ?? this.fontFamily,
1253
      fontSize: (fontSize ?? this.fontSize ?? _kDefaultFontSize) * textScaleFactor,
1254
      height: height ?? this.height,
1255
      textHeightBehavior: effectiveTextHeightBehavior,
1256 1257 1258
      strutStyle: strutStyle == null ? null : ui.StrutStyle(
        fontFamily: strutStyle.fontFamily,
        fontFamilyFallback: strutStyle.fontFamilyFallback,
1259
        fontSize: strutStyle.fontSize == null ? null : strutStyle.fontSize! * textScaleFactor,
1260 1261 1262 1263 1264 1265
        height: strutStyle.height,
        leading: strutStyle.leading,
        fontWeight: strutStyle.fontWeight,
        fontStyle: strutStyle.fontStyle,
        forceStrutHeight: strutStyle.forceStrutHeight,
      ),
1266
      maxLines: maxLines,
1267
      ellipsis: ellipsis,
1268
      locale: locale,
1269 1270
    );
  }
1271

1272 1273 1274 1275 1276 1277 1278
  /// Describe the difference between this style and another, in terms of how
  /// much damage it will make to the rendering.
  ///
  /// See also:
  ///
  ///  * [TextSpan.compareTo], which does the same thing for entire [TextSpan]s.
  RenderComparison compareTo(TextStyle other) {
1279
    if (identical(this, other)) {
1280
      return RenderComparison.identical;
1281
    }
1282 1283 1284 1285 1286 1287 1288 1289
    if (inherit != other.inherit ||
        fontFamily != other.fontFamily ||
        fontSize != other.fontSize ||
        fontWeight != other.fontWeight ||
        fontStyle != other.fontStyle ||
        letterSpacing != other.letterSpacing ||
        wordSpacing != other.wordSpacing ||
        textBaseline != other.textBaseline ||
1290
        height != other.height ||
1291
        leadingDistribution != other.leadingDistribution ||
1292
        locale != other.locale ||
1293
        foreground != other.foreground ||
1294
        background != other.background ||
1295
        !listEquals(shadows, other.shadows) ||
1296
        !listEquals(fontFeatures, other.fontFeatures) ||
1297
        !listEquals(fontVariations, other.fontVariations) ||
1298
        !listEquals(fontFamilyFallback, other.fontFamilyFallback) ||
1299
        overflow != other.overflow) {
1300
      return RenderComparison.layout;
1301
    }
1302
    if (color != other.color ||
1303
        backgroundColor != other.backgroundColor ||
1304 1305
        decoration != other.decoration ||
        decorationColor != other.decorationColor ||
1306
        decorationStyle != other.decorationStyle ||
1307
        decorationThickness != other.decorationThickness) {
1308
      return RenderComparison.paint;
1309
    }
1310 1311 1312
    return RenderComparison.identical;
  }

1313
  @override
1314
  bool operator ==(Object other) {
1315
    if (identical(this, other)) {
1316
      return true;
1317 1318
    }
    if (other.runtimeType != runtimeType) {
Hixie's avatar
Hixie committed
1319
      return false;
1320
    }
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    return other is TextStyle
        && other.inherit == inherit
        && other.color == color
        && other.backgroundColor == backgroundColor
        && other.fontSize == fontSize
        && other.fontWeight == fontWeight
        && other.fontStyle == fontStyle
        && other.letterSpacing == letterSpacing
        && other.wordSpacing == wordSpacing
        && other.textBaseline == textBaseline
        && other.height == height
1332
        && other.leadingDistribution == leadingDistribution
1333 1334 1335
        && other.locale == locale
        && other.foreground == foreground
        && other.background == background
1336 1337
        && listEquals(other.shadows, shadows)
        && listEquals(other.fontFeatures, fontFeatures)
1338
        && listEquals(other.fontVariations, fontVariations)
1339 1340 1341 1342
        && other.decoration == decoration
        && other.decorationColor == decorationColor
        && other.decorationStyle == decorationStyle
        && other.decorationThickness == decorationThickness
1343
        && other.fontFamily == fontFamily
1344
        && listEquals(other.fontFamilyFallback, fontFamilyFallback)
1345
        && other._package == _package
1346
        && other.overflow == overflow;
1347 1348
  }

1349
  @override
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
  int get hashCode => Object.hash(
    inherit,
    color,
    backgroundColor,
    fontSize,
    fontWeight,
    fontStyle,
    letterSpacing,
    wordSpacing,
    textBaseline,
    height,
    leadingDistribution,
    locale,
    foreground,
    background,
    shadows == null ? null : Object.hashAll(shadows!),
    fontFeatures == null ? null : Object.hashAll(fontFeatures!),
1367
    fontVariations == null ? null : Object.hashAll(fontVariations!),
1368 1369 1370
    decoration,
    decorationColor,
    Object.hash(
1371
      decorationStyle,
1372 1373
      decorationThickness,
      fontFamily,
1374
      fontFamilyFallback == null ? null : Object.hashAll(fontFamilyFallback!),
1375
      _package,
1376
      overflow,
1377 1378
    ),
  );
1379

1380
  @override
1381
  String toStringShort() => objectRuntimeType(this, 'TextStyle');
1382 1383

  /// Adds all properties prefixing property names with the optional `prefix`.
1384
  @override
1385
  void debugFillProperties(DiagnosticPropertiesBuilder properties, { String prefix = '' }) {
1386
    super.debugFillProperties(properties);
1387
    if (debugLabel != null) {
1388
      properties.add(MessageProperty('${prefix}debugLabel', debugLabel!));
1389
    }
1390 1391 1392 1393 1394 1395 1396
    final List<DiagnosticsNode> styles = <DiagnosticsNode>[
      ColorProperty('${prefix}color', color, defaultValue: null),
      ColorProperty('${prefix}backgroundColor', backgroundColor, defaultValue: null),
      StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false),
      IterableProperty<String>('${prefix}familyFallback', fontFamilyFallback, defaultValue: null),
      DoubleProperty('${prefix}size', fontSize, defaultValue: null),
    ];
1397
    String? weightDescription;
Hixie's avatar
Hixie committed
1398
    if (fontWeight != null) {
1399
      weightDescription = '${fontWeight!.index + 1}00';
Hixie's avatar
Hixie committed
1400
    }
1401 1402 1403
    // TODO(jacobr): switch this to use enumProperty which will either cause the
    // weight description to change to w600 from 600 or require existing
    // enumProperty to handle this special case.
1404
    styles.add(DiagnosticsProperty<FontWeight>(
1405 1406 1407 1408 1409
      '${prefix}weight',
      fontWeight,
      description: weightDescription,
      defaultValue: null,
    ));
1410 1411 1412 1413 1414
    styles.add(EnumProperty<FontStyle>('${prefix}style', fontStyle, defaultValue: null));
    styles.add(DoubleProperty('${prefix}letterSpacing', letterSpacing, defaultValue: null));
    styles.add(DoubleProperty('${prefix}wordSpacing', wordSpacing, defaultValue: null));
    styles.add(EnumProperty<TextBaseline>('${prefix}baseline', textBaseline, defaultValue: null));
    styles.add(DoubleProperty('${prefix}height', height, unit: 'x', defaultValue: null));
1415
    styles.add(EnumProperty<ui.TextLeadingDistribution>('${prefix}leadingDistribution', leadingDistribution, defaultValue: null));
1416 1417 1418
    styles.add(DiagnosticsProperty<Locale>('${prefix}locale', locale, defaultValue: null));
    styles.add(DiagnosticsProperty<Paint>('${prefix}foreground', foreground, defaultValue: null));
    styles.add(DiagnosticsProperty<Paint>('${prefix}background', background, defaultValue: null));
1419
    if (decoration != null || decorationColor != null || decorationStyle != null || decorationThickness != null) {
1420
      final List<String> decorationDescription = <String>[];
1421
      if (decorationStyle != null) {
1422
        decorationDescription.add(decorationStyle!.name);
1423
      }
1424 1425 1426

      // Hide decorationColor from the default text view as it is shown in the
      // terse decoration summary as well.
1427
      styles.add(ColorProperty('${prefix}decorationColor', decorationColor, defaultValue: null, level: DiagnosticLevel.fine));
1428

1429
      if (decorationColor != null) {
1430
        decorationDescription.add('$decorationColor');
1431
      }
1432 1433 1434 1435

      // Intentionally collide with the property 'decoration' added below.
      // Tools that show hidden properties could choose the first property
      // matching the name to disambiguate.
1436
      styles.add(DiagnosticsProperty<TextDecoration>('${prefix}decoration', decoration, defaultValue: null, level: DiagnosticLevel.hidden));
1437
      if (decoration != null) {
1438
        decorationDescription.add('$decoration');
1439
      }
1440
      assert(decorationDescription.isNotEmpty);
1441
      styles.add(MessageProperty('${prefix}decoration', decorationDescription.join(' ')));
1442
      styles.add(DoubleProperty('${prefix}decorationThickness', decorationThickness, unit: 'x', defaultValue: null));
Hixie's avatar
Hixie committed
1443
    }
1444

1445
    final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info));
1446
    properties.add(DiagnosticsProperty<bool>('${prefix}inherit', inherit, level: (!styleSpecified && inherit) ? DiagnosticLevel.fine : DiagnosticLevel.info));
1447
    styles.forEach(properties.add);
1448

1449
    if (!styleSpecified) {
1450
      properties.add(FlagProperty('inherit', value: inherit, ifTrue: '$prefix<all styles inherited>', ifFalse: '$prefix<no style specified>'));
1451
    }
1452 1453

    styles.add(EnumProperty<TextOverflow>('${prefix}overflow', overflow, defaultValue: null));
1454 1455
  }
}