formatted method
Formats the string with the given arguments.
Supports %s
, %d
, %f
, and %n
placeholders using either:
- Positional arguments (e.g.
formatted("Alice", 42)
) - A single list of arguments (e.g.
formatted(["Alice", 42])
)
Example:
'Hello, %s. You have %d new messages.%n'.formatted('Alice', 5);
Outputs:
Hello, Alice. You have 5 new messages.
Supports usage like:
'%s %d %f %n'.formatted('hi', 2, 3.14);
'%s %s'.formatted(['a', 'b']);
Implementation
String formatted([Object? arg1, Object? arg2, Object? arg3, Object? arg4, Object? arg5, Object? arg6, Object? arg7, Object? arg8]) {
final args = _normalizeArgs([arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8]);
final parts = split(RegExp(r'(%[sdfn])'));
final buffer = StringBuffer();
var argIndex = 0;
for (var part in parts) {
if (_isPlaceholder(part)) {
if (argIndex < args.length) {
buffer.write(_formatPlaceholder(part, args[argIndex]));
argIndex++;
} else {
buffer.write(part); // Leave placeholder as-is
}
} else {
buffer.write(part);
}
}
return buffer.toString();
}