Dart String padLeft()
Syntax & Examples


Syntax of String.padLeft()

The syntax of String.padLeft() method is:

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

This padLeft() method of String pads this string on the left if it is shorter than width.

Parameters

ParameterOptional/RequiredDescription
widthrequiredthe total width of the resulting string after padding
paddingoptional [default value is ' ']the padding character used to fill the remaining spaces

Return Type

String.padLeft() returns value of type String.



✐ Examples

1 Pad number with leading zeroes

In this example,

  1. We create a string str with the value '123'.
  2. We use the padLeft() method with a width of 5 and padding character '0' to pad the string on the left.
  3. Since the original string length is less than 5, it gets padded with leading zeroes.
  4. We print the padded string to standard output.

Dart Program

void main() {
  String str = '123';
  String paddedStr1 = str.padLeft(5, '0');
  print('Padded string: $paddedStr1');
}

Output

Padded string: 00123

2 Pad string with leading asterisks

In this example,

  1. We create a string str with the value 'Hello'.
  2. We use the padLeft() method with a width of 10 and padding character '*' to pad the string on the left.
  3. Since the original string length is less than 10, it gets padded with leading asterisks.
  4. We print the padded string to standard output.

Dart Program

void main() {
  String str = 'Hello';
  String paddedStr2 = str.padLeft(10, '*');
  print('Padded string: $paddedStr2');
}

Output

Padded string: *****Hello

3 Pad string with default leading spaces

In this example,

  1. We create a string str with the value 'Dart'.
  2. We use the padLeft() method with a width of 7 without specifying a padding character (defaults to spaces).
  3. Since the original string length is less than 7, it gets padded with leading spaces.
  4. We print the padded string to standard output.

Dart Program

void main() {
  String str = 'Dart';
  String paddedStr3 = str.padLeft(7); // default padding with spaces
  print('Padded string: $paddedStr3');
}

Output

Padded string:    Dart

Summary

In this Dart tutorial, we learned about padLeft() method of String: the syntax and few working examples with output and detailed explanation for each example.