joinToString method
Creates a string from all the elements separated using separator and
using the given prefix and postfix if supplied.
If the collection could be huge, you can specify a non-negative value of
limit, in which case only the first limit elements will be appended,
followed by the truncated string (which defaults to '...').
Parameters: separator (String): The separator string to use between elements. Defaults to ', '. transform (Function(T element)?): An optional function to transform each element to a string. prefix (String): A prefix to add before each element. Defaults to an empty string. postfix (String): A postfix to add after each element. Defaults to an empty string. limit (int): The maximum number of elements to include in the result. Defaults to 0 (no limit). truncated (String): A string to append after the last element if the limit is reached. Defaults to '...'.
Returns: String: A string representation of the elements, transformed and separated as specified.
Example:
List<int> numbers = [1, 2, 3, 4, 5];
String result = numbers.joinToString(separator: "; ", prefix: "<", postfix: ">");
// Output: "<1>; <2>; <3>; <4>; <5>"
Implementation
String joinToString({
String separator = ', ',
String Function(T element)? transform,
String prefix = '',
String postfix = '',
int limit = 0,
String truncated = '...',
}) {
var buffer = StringBuffer();
var count = 0;
for (var element in this) {
if (limit > 0 && count >= limit) {
buffer.write(truncated);
break;
}
if (count > 0) {
buffer.write(separator);
}
buffer.write(prefix);
if (transform != null) {
buffer.write(transform(element));
} else {
buffer.write(element.toString());
}
buffer.write(postfix);
count++;
}
return buffer.toString();
}