How to use new line character in Text Widget Flutter

For me, when getting data with '\n' in the text from the local sqlite database, this worked:

    var message = await db.getDataFromDB();
    return Text(message.replaceAll('\\n', '\n'))

If you want to break line with a string that comes from outside the Flutter you should modify the string inside flutter.

So if you get from API a string 'Order received! \n Wait in the line!' and the break line is not working, in flutter you should replace the '\n' inside flutter

var response = await getMessageFromServer();
String message = getMessage(response);
return Text(message.replaceAll('\n', '\n'))

This way you will see how the color of '\n' is different in flutter.

I prefered using '/n' for the API and then in flutter I replace.all('/n', '\n')


Approach 1 Using Triple quotes

      child: Container(
         child :  Text('''
                          Text1
                          Text2
                          Text3''',maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )
      ),

Approach 2 Using \n here is example with Dynamic String :

        var readLines = ['Test1', 'Test2', 'Test3'];
        String getNewLineString() {
           StringBuffer sb = new StringBuffer();
           for (String line in readLines) {
              sb.write(line + "\n");
           }
           return sb.toString();
        }


        child: Container(
           child: Text(
          getNewLineString(),
          maxLines: 20,
          style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: Colors.black),
        )),

Approach 3 using static text with \n

  Text('Welcome\nto\nMyWorld\nHello\nWorld\n');

For more, you should refer to this link https://api.dartlang.org/stable/2.5.0/dart-core/String-class.html

Tags:

Flutter