merge method Null safety

TextTheme merge(
  1. TextTheme? other

Creates a new TextTheme where each text style from this object has been merged with the matching text style from the other object.

The merging is done by calling TextStyle.merge on each respective pair of text styles from this and the other text themes and is subject to the value of TextStyle.inherit flag. For more details, see the documentation on TextStyle.merge and TextStyle.inherit.

If this theme, or the other theme has members that are null, then the non-null one (if any) is used. If the other theme is itself null, then this TextTheme is returned unchanged. If values in both are set, then the values are merged using TextStyle.merge.

This is particularly useful if one TextTheme defines one set of properties and another defines a different set, e.g. having colors defined in one text theme and font sizes in another, or when one TextTheme has only some fields defined, and you want to define the rest by merging it with a default theme.

/// A Widget that sets the ambient theme's title text color for its
/// descendants, while leaving other ambient theme attributes alone.
class TitleColorTheme extends StatelessWidget {
  const TitleColorTheme({Key? key, required this.child, required this.titleColor}) : super(key: key);

  final Color titleColor;
  final Widget child;

  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    // This partialTheme is incomplete: it only has the title style
    // defined. Just replacing theme.textTheme with partialTheme would
    // set the title, but everything else would be null. This isn't very
    // useful, so merge it with the existing theme to keep all of the
    // preexisting definitions for the other styles.
    final TextTheme partialTheme = TextTheme(headline6: TextStyle(color: titleColor));
    theme = theme.copyWith(textTheme: theme.textTheme.merge(partialTheme));
    return Theme(data: theme, child: child);

See also:


TextTheme merge(TextTheme? other) {
  if (other == null)
    return this;
  return copyWith(
    headline1: headline1?.merge(other.headline1) ?? other.headline1,
    headline2: headline2?.merge(other.headline2) ?? other.headline2,
    headline3: headline3?.merge(other.headline3) ?? other.headline3,
    headline4: headline4?.merge(other.headline4) ?? other.headline4,
    headline5: headline5?.merge(other.headline5) ?? other.headline5,
    headline6: headline6?.merge(other.headline6) ?? other.headline6,
    subtitle1: subtitle1?.merge(other.subtitle1) ?? other.subtitle1,
    subtitle2: subtitle2?.merge(other.subtitle2) ?? other.subtitle2,
    bodyText1: bodyText1?.merge(other.bodyText1) ?? other.bodyText1,
    bodyText2: bodyText2?.merge(other.bodyText2) ?? other.bodyText2,
    caption: caption?.merge(other.caption) ?? other.caption,
    button: button?.merge(other.button) ?? other.button,
    overline: overline?.merge(other.overline) ?? other.overline,