center function

String center(
  1. String? input,
  2. int width,
  3. String fill
)

Returns a String of length width padded with the same number of characters on the left and right from fill. On the right, characters are selected from fill starting at the end so that the last character in fill is the last character in the result. fill is repeated if necessary to pad.

Returns input if input.length is equal to or greater than width. input can be null and is treated as an empty string.

If there are an odd number of characters to pad, then the right will be padded with one more than the left.

Implementation

String center(String? input, int width, String fill) {
  if (fill.isEmpty) {
    throw ArgumentError('fill cannot be empty');
  }
  input ??= '';
  if (input.length >= width) return input;

  var padding = width - input.length;
  if (padding ~/ 2 > 0) {
    input = loop(fill, 0, padding ~/ 2) + input;
  }
  return input + loop(fill, input.length - width, 0);
}