Flutter \n\n not breaking lines unless hard-coded string - flutter

I can see that Flutter allows me to use "\n\n" in a string and it causes a line break to appear in a Text item:
final String answer = "This is my text.\n\n"
"Here is the 2nd line.";
This is my text.
Here is the 2nd line.
However, when I try to use content pulled from firebase, and set in a variable, the line break ("\n") is actually printed:
final String answer = faq['answer'];
Shows:
This is my text.\n\nHere is the 2nd line.
How can I get my "\n\n" to actually show up as line breaks?

Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it.
So you can try something like this:
final String answer = (faq['answer'] as String).replaceAll("\\n", "\n");

Related

Flutter text output not throwing paragraph line when comes from Firebase

I have a Text widget, with \n\n in it to throw a blank line when the paragraph changes:
Text('Sibling Rivalry \n\n some more text\n\n> and even more text')
This works fine and prints blank lines where the \n\n are defined. However when I try to output the exact same text, but retrieved from Cloud Firestore, the blank lines are not thrown.
Here's the loading code:
final extracted = await _firestore
.collection('items')
.where("active", isEqualTo: true)
.orderBy("playCount", descending: true)
.getDocuments();
extracted.documents.forEach(
(mediaData) {
if (mediaData['itemType'] == 'V') {
loadedMedia.add(
MediaItem(
// load fields for VIDEO,
title: mediaData['title'],
description: mediaData['description'],
itemCatCode: mediaData['itemCatCode'],
imageUrl: mediaData['imageUrl'],
itemUrl: mediaData['itemUrl'],
itemType: mediaData['itemType'],
),
);
}
And then I try to output it to screen via the same Text widget:
Text(mediaItem.description),
Btw I am typing the text directly into Firestore and the description field is defined as String in Firestore. I have no idea why the /n/n is not being recognized as the string coming from Firestore looks exactly the same as the hardcoded string above.
Any help with this would really be greatly appreciated as in the final app, there is a lot of text with quite a few paragraphs.
Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it. If you need to store something special, you may want to encode and decode that yourself.
just do mediaItem.description replace "\n" with: "\n" again (if you have created string using \n)
One more thing you can try mediaItem.description replace "\\n" with: "\n" (if it was automatically created using some textarea etc)

Flutter Unicode Apostrophe In String

I'm hoping this is an easy question, and that I'm just not seeing the forest due to all the trees.
I have a string in flutter than came from a REST API that looks like this:
"What\u0027s this?"
The \u is causing a problem.
I can't do a string.replaceAll("\", "\") on it as the single slash means it's looking for a character after it, which is not what I need.
I tried doing a string.replaceAll(String.fromCharCode(0x92), "") to remove it - That didn't work.
I then tried using a regex to remove it like string.replaceAll("/(?:\)/", "") and the same single slash remains.
So, the question is how to remove that single slash, so I can add in a double slash, or replace it with a double slash?
Cheers
Jase
I found the issue. I was looking for hex 92 (0x92) and it should have been decimal 92.
I ended up solving the issue like this...
String removeUnicodeApostrophes(String strInput) {
// First remove the single slash.
String strModified = strInput.replaceAll(String.fromCharCode(92), "");
// Now, we can replace the rest of the unicode with a proper apostrophe.
return strModified.replaceAll("u0027", "\'");
}
When the string is read, I assume what's happening is that it's being interpreted as literal rather than as what it should be (code points) i.e. each character of \0027 is a separate character. You may actually be able to fix this depending on how you access the API - see the dart convert library. If you use utf8.decode on the raw data you may be able to avoid this entire problem.
However, if that's not an option there's an easy enough solution for you.
What's happening when you're writing out your regex or replace is that you're not escaping the backslash, so it's essentially becoming nothing. If you use a double slash, that solve the problem as it escapes the escape character. "\\" => "\".
The other option is to use a raw string like r"\" which ignores the escape character.
Paste this into https://dartpad.dartlang.org:
String withapostraphe = "What\u0027s this?";
String withapostraphe1 = withapostraphe.replaceAll('\u0027', '');
String withapostraphe2 = withapostraphe.replaceAll(String.fromCharCode(0x27), '');
print("Original encoded properly: $withapostraphe");
print("Replaced with nothing: $withapostraphe1");
print("Using char code for ': $withapostraphe2");
String unicodeNotDecoded = "What\\u0027s this?";
String unicodeWithApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '\'');
String unicodeNoApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '');
String unicodeRaw = unicodeNotDecoded.replaceAll(r"\u0027", "'");
print("Data as read with escaped unicode: $unicodeNotDecoded");
print("Data replaced with apostraphe: $unicodeWithApostraphe");
print("Data replaced with nothing: $unicodeNoApostraphe");
print("Data replaced using raw string: $unicodeRaw");
To see the result:
Original encoded properly: What's this?
Replaced with nothing: Whats this?
Using char code for ': Whats this?
Data as read with escaped unicode: What\u0027s this?
Data replaced with apostraphe: What's this?
Data replaced with nothing: Whats this?
Data replaced using raw string: What's this?

New Line Command (\n) Not Working With Firebase Firestore Database Strings

I'm making an app with Swift and I'm using Firebase Firestore. Firestore is a database that has some strings that I put into a UILabel. With some of my strings, I am using the new line command (or \n). So some of my strings look like this:
"This is line one\nThis is line two\nThis is line three"
But, whenever that string is retrieved, it's addetoto the UILabel and appears like this...
This is line one\nThis is line two\nThis is line three
...when it should be like this...
This is line one
This is line two
This is line three
I'm assuming that \n does not work with strings coming from a database? I've tried double escaping with \\n. Does anyone have a fix for this?
Here is the code that I am using...
database.collection("songs").whereField("storyTitle", isEqualTo: "This is the story header").getDocuments { (snapshot, error) in
for document in (snapshot?.documents)! {
self.storyBodyLabel.text = (document.data()["storyBody"] as? String)!
}
}
I got it. I simply just replaced the character "\n" from the string that I was receiving with the newline command.
label.text = stringRecived.replacingOccurrences(of: "\n", with: "\n")
Because I manually typed out my string and gave Firebase a string like
"Line one\nline two\nline three" I am replacing "\n" with "\n" But if you give Firebase a string like
"Line one
Line two
Line three"
Firebase replaces those returns with "\\n" therfore making the code
label.text = stringRecived.replacingOccurrences(of: "\\n", with: "\n")
Hope that helps!
You can use CSS whitespace property for \n, it works for me.
white-space: pre-line;
Solution: Add this to your string and you are done (for Java users):
.replace("\\n", "\n")
Example:
if (dataSnapshot.exists())
{
ArrayList<String> userlogs2 = new ArrayList<String>();
userlogs2.add(dataSnapshot.getValue().toString().replace("\\n", "\n"));
Iterator<String> it2 = userlogs2.iterator();
while (it2.hasNext()) {
appendColoredText(userlogsmessages2, it2.next() + "\n", Color.BLACK);
appendUnderlinedText(userlogsmessages2,"____________" + "\n\n", Color.parseColor("#DB808080"));
}
Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it. If you need to store something special, you may want to encode and decode that yourself.
Tried all of the answers suggested but none worked for me. In the end, I fixed it by using "/n" in the Firestore record and, in the Swift client, the following:
label.text = stringReceived.replacingOccurrences(of: "/n", with: "\n")
For me firebase turned all \n to \\\\n , so I just reversed that change with :
theString.replaceAll( "\\\\n", "\n" );
Just posting cause I wasted some time calculating the right number of '\'
I found I could get newlines into a firestore field by using the String.fromCharCode() function. Firestore seems to need special characters in strings to be the actual character ASCII values and does not reinterpret escape characters.
i.e.
"First Line " + String.fromCharCode(13) + "second line"
100% Working
DB.collection(Global.DB_COLLECTION_PATH).document(NEWS_ID).get().addOnCompleteListener(new OnCompleteListener< DocumentSnapshot >() {
#Override
public void onComplete(#NonNull Task< DocumentSnapshot > task) {
if (task.isSuccessful()) {
body1 = task.getResult().getString("newsBody").replace("\n", "\n");
nBody.setText(body1);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("DB FAILED", e.getMessage());
}
});
I hope it's work for you
I noticed that when you add a string with \n to the JSON export and then upload the JSON to the Realtime Database, it acts as a newline. But if you edit that from the firebase console, it gives you back the string with \n and not a newline.
Firestore add this type----Line one\nline two\nline three
get Sting, replace and show with TextView
String sura=modellist.get(position).getSura().replace( "\n", "\n");
Working..

How to add escape character in string?

editedDate = `"16/11/2016 10:58:11"`
I want to send above string to server with escape character.
let revisedText = editedDate.replacingOccurrences(of: "/", with: "\\/")
Still i get value as
"16\\/11\\/2016 10:58:11"
I want
"16\/11\/2016 10:58:11"
The value is actually correct. Here is the output of the playground when printing the variable:
However, you may just have seen the value in the sidebar if you are using playground or in LLDB:
In that way, you can see the escape character is shown (\). Actually, it's not there. You can safely send the string to the server.
Your code is correct. Use print to show the modified string on console. Debugger or REPL will escape the output, too, e.g. lldb:
(lldb) po editedDate.replacingOccurrences(of: "/", with: "\\/")
"16\\/11\\/2016 10:58:11"
(lldb) p print(editedDate.replacingOccurrences(of: "/", with: "\\/"))
16\/11\/2016 10:58:11

How do I maintain a string linebreak through a PlayerPref?

I am printing code to a TextMesh, and it is always changing. I need to save the string to a PlayerPref, so that I can load it back up. In order to get the text to fit properly, I have to force a line break in the string, using \n.
string text = "line1\nline2";
PlayerPref.SetString("Text", text);
LocationSide1.GetComponent<TextMesh>().text = PlayerPrefs.GetString("Text");
If I set the text without the PlayerPref it will do a line break:
line1
line2
With the PlayerPref it prints as one line:
line1\nline2
Any ideas on how to fix this?
Seems like the '\' is escaped.
Have you tried to unescape the string ?
using System.Text.RegularExpressions;
[...]
string text = "line1\nline2";
PlayerPref.SetString("Text", text);
LocationSide1.GetComponent<TextMesh>().text = Regex.Unescape(PlayerPrefs.GetString("Text"));
myString = Regex.Unescape(myString);