长文本强制换行

pet*_*ter 1 flutter

Text在以下情况下,当屏幕不适合时,有没有办法自动断行文本?

Row(
 children: [
  SizedBox(width: 40, height:40),
  Container(
   child: Text("Long text without explicit line breaks, but still long.")
  )
  SizedBox(width: 40, height:40)
 ]
)
Run Code Online (Sandbox Code Playgroud)

小智 10

你有两种方法可以做到这一点。

1. 将你的 Widget Text 包裹在一个 Container 中,并为他设置宽度,例如:


     final mediaQuery = MediaQuery.of(context);
    
     return Container (
      padding: const EdgeInsets.all(10.0),
      width: mediaQuery.size.width * 0.05,
      child: new Column (
        children: <Widget>[
          new Text ("Long text without explicit line breaks, but still long.", textAlign: TextAlign.left)
        ],
      ),
    );

Run Code Online (Sandbox Code Playgroud)

OBS:我使用 mediaQuery 来实现响应性,但您可以设置一个固定值

2. 您可以使用灵活的小部件进行换行:

但Flexible需要与Row、Column或Flex小部件一起使用,否则会引发异常。

       new Container(
           child: Row(
             children: <Widget>[
                Flexible(
                   child: new Text("Long text without explicit line breaks, but still long."),
                    ),
                ],
            ),
        );
Run Code Online (Sandbox Code Playgroud)