flutter

Flutter - Trim a String

In Flutter, you can trim a string using the trim() method provided by the Dart programming language. The trim() method removes any leading and trailing whitespace characters from the string.


Here's an example of how you can trim a string in Flutter:

String myString = "  Hello, World!   ";
String trimmedString = myString.trim();
print(trimmedString);

Output

"Hello, World!"

In the above example, the trim() method is called on the myString variable, which removes the leading and trailing spaces from the string. The resulting trimmed string is stored in the trimmedString variable. Finally, the trimmed string is printed to the console.

Remove specific characters from the beginning or end of a string

If you want to remove specific characters from the beginning or end of a string, you can use the trimLeft() and trimRight() methods respectively. Here's an example:

String myString = "*Hello, World!*";
String trimmedString = myString.trimLeft('*').trimRight('*');
print(trimmedString);

Output

"Hello, World!"

In this example, the trimLeft('*') method removes leading asterisks, and the trimRight('*') method removes trailing asterisks from the string. The resulting trimmed string is printed to the console.

Was this helpful?