merge static method Null safety

Widget merge(
  1. {Key? key,
  2. TextStyle? style,
  3. TextAlign? textAlign,
  4. bool? softWrap,
  5. TextOverflow? overflow,
  6. int? maxLines,
  7. TextWidthBasis? textWidthBasis,
  8. required Widget child}
)

Creates a default text style that overrides the text styles in scope at this point in the widget tree.

The given style is merged with the style from the default text style 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.

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 DefaultTextStyle.new constructor directly. See the source below for an example of how to do this (since that's essentially what this constructor does).

Implementation

static Widget merge({
  Key? key,
  TextStyle? style,
  TextAlign? textAlign,
  bool? softWrap,
  TextOverflow? overflow,
  int? maxLines,
  TextWidthBasis? textWidthBasis,
  required Widget child,
}) {
  assert(child != null);
  return Builder(
    builder: (BuildContext context) {
      final DefaultTextStyle parent = DefaultTextStyle.of(context);
      return DefaultTextStyle(
        key: key,
        style: parent.style.merge(style),
        textAlign: textAlign ?? parent.textAlign,
        softWrap: softWrap ?? parent.softWrap,
        overflow: overflow ?? parent.overflow,
        maxLines: maxLines ?? parent.maxLines,
        textWidthBasis: textWidthBasis ?? parent.textWidthBasis,
        child: child,
      );
    },
  );
}