You are asking for a way to escape newlines (and possibly other control characters) in a string value.
There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode
is an adequate substitute.
So, given your string
containing a newline, you can convert it to a string containing \n
(a backslash and an n
) as var escapedString = jsonEncode(string);
. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);
.
Alternatively, if you only care about newlines, you can just replace them yourself:
var myString = string.replaceAll("\n", r"\n");
String s = r"Hello \n World";
?