Dart - Pad Left and Right a String

Do you need to pad a String either to left or right using Dart? Find out in this tutorial.

Sometimes it's necessary to pad a String so that it has at least a certain minimum of length. In Dart, it's very easy to do it by using padLeft and padRight which adds character padding on the left and right side respectively.

Using padLeft

It is used to pad left a String if it's shorter than the specified width. By default (space) is used as the padding character, but you can override the character to be used by passing padding option.

  String padLeft(int width, [String padding = ' ']);

For example, there is a String with 6 characters.

  String s = "woolha";

  // A1
  print(s.padLeft(10)); // '    woolha'

  // A2
  print(s.padLeft(10, '.')); // '....woolha'

  // A3
  print(s.padLeft(10, ',.*')); // ',.*,.*,.*,.*woolha'

  // A4
  print(s.padLeft(3, '.')); // 'woolha'

In the example A1, as padding option is not passed, the default character (space) is used. As it has 6 characters, it means 4 more is needed to make it 10. Therefore, there are 4 spaces added at the front.

In the example A2, . is set as the padding character replacing space.

In the example A3, multiple characters is passed. As you can see, the result becomes more than 10 characters as the multi-char String is also added 4 times.

In the example A4, the width is lower than the length of the String. As the result, nothing is added and the length remains 6. Setting the width value to be lower than 0 will result the same as it will be treated as 0.

Using padRight

padRight is used to add padding character on the right. It has the same parameters:

  String padRight(int width, [String padding = ' ']);
  print(s.padRight(10));  // 'woolha    '
  print(s.padRight(10, '.')); // 'woolha....' 
  print(s.padRight(10, ',.*')); // 'woolha,.*,.*,.*,.*'
  print(s.padRight(3, '.')); // 'woolha'

Apart from where the padding characters are added, the behavior is the same as padLeft, so I will not explain it again.

If the String can be null, it's better to use null-aware operator by adding ? before . (dot). It will return null if the String is null;

  String x = null;
  print(x?.padLeft(10, '.'));
Output:
  null