This is what I came up with. If there is a better way, let me know.
Asked
Active
Viewed 4.8k times
43
-
1Just curious, why do some people post their questions(that they already have answers to) and supply an answer immediately ? @live-love – void May 18 '20 at 19:14
-
To share knowledge? – live-love May 18 '20 at 19:15
-
2Ohh cool. I totally understand now. Thanks @live-love – void May 18 '20 at 19:15
-
1Does this answer your question? [How to remove the last character from a string?](https://stackoverflow.com/questions/7438612/how-to-remove-the-last-character-from-a-string) – Yudhishthir Singh May 18 '20 at 19:43
-
That's in java, I was looking for a dart solution and didn't find one. – live-love May 18 '20 at 20:10
-
1https://stackoverflow.com/questions/55905889/how-to-get-the-last-n-characters-in-a-string-in-dart – May 18 '20 at 20:38
-
Guess I missed it, I will try to close the question. – live-love May 19 '20 at 16:47
2 Answers
89
Remove last character:
if (str != null && str.length > 0) {
str = str.substring(0, str.length - 1);
}
Remove last 5 characters:
if (str != null && str.length >= 5) {
str = str.substring(0, str.length - 5);
}

live-love
- 48,840
- 22
- 240
- 204
-
1The test for `str.endsWith('x')` seems not relevant to the question. The question is "remove the last character(s)" not "remove the last character(s) if the string ends with x". – julemand101 May 18 '20 at 19:27
-
I think removing nothing from "Hi" in the 5-characters-case is rather surprising, but depends on the use case, I quess. – Eiko May 20 '20 at 11:33
0
The answer that you have given would suffice the problem, just wanted to share this another way to remove the last element. Here I am using removeLast function provided by the dart library.
This function can be used on any list to remove the last element.
void main() {
String x = "aaabcd";
List<String> c = x.split(""); // ['a', 'a', 'a', 'b', 'c', 'd']
c.removeLast(); // ['a', 'a', 'a', 'b', 'c']
print(c.join()); //aaabc
}

Yudhishthir Singh
- 2,941
- 2
- 23
- 42