Flutter: Excess space on multiline Text widgets
Asked Answered
A

1

7

I have Text widget that is being constrained by Container with BoxConstraints, and I noticed that when the text has multiple lines, there is excess spacing (on the right) due to the overflow.

Text widget with overlay

The code for this, minus styling, is simple:

Container(
  constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * (2/3)),
  child: Padding(
    padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
    child: Text(
      message
    ),
  ),
)

You can see the space to the right of the text. Looking at the overlay, it looks like this is the intended behavior, but is there any way to constrain the Widget to remove the excess space?

Apologetics answered 18/6, 2020 at 21:50 Comment(0)
D
5

You are looking for the proprety: textWidthBasis. Set it TextWidthBasis.longestLine and the text width will resize based on the longestLine hence removing the blank space on the right.

Text("Why don't you I set up an appointment and we can discuss this further...",
                  textWidthBasis: TextWidthBasis.longestLine,),

enter image description here

Full code:

class MultiLinee extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          color: Colors.grey,
          child: Container(
            constraints: BoxConstraints(maxWidth: MediaQuery
                .of(context)
                .size
                .width * (2 / 3)),
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
              child: Container(
                color: Colors.yellow,
                child: Text("Why don't you I set up an appointment and we can discuss this further...",
                  textWidthBasis: TextWidthBasis.longestLine,),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
Dorcy answered 18/6, 2020 at 23:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.