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
.
Parameter | Optional/Required | Description |
---|---|---|
width | required | the total width of the resulting string after padding |
padding | optional [default value is ' '] | the padding character used to fill the remaining spaces |
String.padLeft() returns value of type String
.
In this example,
str
with the value '123'.padLeft()
method with a width of 5 and padding character '0' to pad the string on the left.void main() {
String str = '123';
String paddedStr1 = str.padLeft(5, '0');
print('Padded string: $paddedStr1');
}
Padded string: 00123
In this example,
str
with the value 'Hello'.padLeft()
method with a width of 10 and padding character '*' to pad the string on the left.void main() {
String str = 'Hello';
String paddedStr2 = str.padLeft(10, '*');
print('Padded string: $paddedStr2');
}
Padded string: *****Hello
In this example,
str
with the value 'Dart'.padLeft()
method with a width of 7 without specifying a padding character (defaults to spaces).void main() {
String str = 'Dart';
String paddedStr3 = str.padLeft(7); // default padding with spaces
print('Padded string: $paddedStr3');
}
Padded string: Dart
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.