Home > database >  Force line break for long text
Force line break for long text

Time:10-01

Is there a way to automatically break lines of text in the following scenario, when Text does not fit on the screen?

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

CodePudding user response:

You've two ways to make that.

1. Wrap your Widget Text in a Container, and set a width for him, like:


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

OBS: I used mediaQuery for reponsivity, but you can set a fix value

2. You can wrap with the Flexible widget:

But Flexible needs to be used with Row, Column or Flex widget, or a exception with be raised.

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

CodePudding user response:

You can wrap the Text in an Expanded widget instead of wrapping it with a container. read more about it here: Flutter- wrapping text

CodePudding user response:

  1. first solution in your code
 Row(children: [
        SizedBox(width: 40, height: 40),
        Expanded(
            child: Text(
                "Long text without explicit line breaks, but still long.")),
        SizedBox(width: 40, height: 40)
      ])
  1. you use the sized box for padding and margin and that's why you used row as a parent, lets make it simple.
Container(
        margin: EdgeInsets.only(top: 40, bottom: 40),
        child: Padding(
          padding: const EdgeInsets.all(40),
          child:
              Text("Long text without explicit line breaks, but still long."),
        ),
      ),
  • Related