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

问题描述 投票:0回答:7

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

Text("Text1\n Text2\n Text3",maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )
flutter
7个回答
90
投票

方法 1 使用三引号

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

方法 2 使用 这是动态字符串的示例:

        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),
        )),

方法 3 使用静态文本

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

欲了解更多,请参考此链接 https://api.dartlang.org/stable/2.5.0/dart-core/String-class.html


28
投票

对我来说,当使用 ' 获取数据时 ' 在本地 sqlite 数据库的文本中,这有效:

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

5
投票

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

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

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

这样你就会看到'的颜色如何 ' 在颤振中是不同的。

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


5
投票

我发现的另一个选择是使用

RichText
小部件,如下所示:

RichText(
  text: TextSpan(
    text: 'A line with a newline character\n',
    children: [
      TextSpan(
        text: 'A second line',
      ),
    ],
  ),
),

2
投票

就用这个

Text('${userInfo.name}'
                        '\n${userInfo.email}'
                        '\n${userInfo.mobilenumber}',maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )

2
投票

您可以在

Text()
小部件中编写多行文本,只需用单独的引号 (" ") 将每行文本括起来即可。 像这样,看截图。

enter image description here


0
投票

如果您从 API、Firebase 等获取任何带有 ' ' 在里面。您可以按照以下步骤操作:

String data = dataFromAPI(); //For eg. it returns "How are you?\nI am good!"
String newData = data.replaceAll('\\n', '\n');

在这里,如果您在任何地方显示 newData,它将添加新行。这适用于您可能从外部接收到 flutter 的任何数据。

© www.soinside.com 2019 - 2024. All rights reserved.