如何在 Text Widget Flutter 中使用换行符

Atm*_*ram 34 flutter

如何在 Flutter 中显示多行文本?

Text("Text1\n Text2\n Text3",maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )
Run Code Online (Sandbox Code Playgroud)

Ami*_*ati 52

方法 1使用三重引号

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

方法 2使用\n此处是使用 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),
        )),
Run Code Online (Sandbox Code Playgroud)

方法 3使用带有 \n 的静态文本

  Text('Welcome\nto\nMyWorld\nHello\nWorld\n');
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您应该参考此链接 https://api.dartlang.org/stable/2.5.0/dart-core/String-class.html

  • 来自服务器的新行字符不起作用,但我在本地再次修改它以将换行符放在需要的地方,它现在可以工作。谢谢。 (2认同)

小智 6

如果你想用来自 Flutter 外部的字符串换行,你应该修改 flutter 内部的字符串。

因此,如果您从 API 获取字符串“订单已收到!” \n 排队等候!' 并且断线不起作用,在 flutter 中您应该替换 flutter 内的 '\n'

var response = await getMessageFromServer();
String message = getMessage(response);
return Text(message.replaceAll('\n', '\n'))
Run Code Online (Sandbox Code Playgroud)

这样你就会看到 '\n' 的颜色在 flutter 中有何不同。

我更喜欢使用 '/n' 作为 API,然后在 flutter 中替换.all('/n', '\n')

  • 你的代码对我不起作用。`.replaceAll(r'\n', '\n')` 有效。 (8认同)

小智 5

对我来说,当从本地 sqlite 数据库的文本中获取带有 '\n' 的数据时,这有效:

    var response = await db.getDataFromDB();
    return Text(message.replaceAll('\\n', '\n'))
Run Code Online (Sandbox Code Playgroud)