Dart – Trim Spaces around String

To trim the leading and trailing whitespace in Dart, call trim() method on this string.

trim() method returns a new string with all the whitespace characters removed from the leading and trailing edges of the given string. The original string remains unchanged.

Syntax

The syntax to call trim() method on this string object str is

</>
Copy
str.trim()

Example

In this example, we take a string with some leading and trailing whitespace, and trim the whitespace using trim() method.

main.dart

</>
Copy
void main() {
  var str = '    Hello World  ';
  var result = str.trim();
  print('Original String : "$str"');
  print('Result String   : "$result"');
}

Output

Original String : "    Hello World  "
Result String   : "Hello World"

Conclusion

In this Dart Tutorial, we learned how to trim whitespace present on the edges of a string, using trim() method of String class, with examples.