flutterdartuser-interfacemessagebox

I'm having problem with coding UI formatting of message box with flutter


Look as you can see here the message box at the bottom should crop to the content but it doesn't as the word doesn't fit so just goes to next line but message box doesn't update.

enter image description here

heres my current code the max width is 0.7 but yeah it should be able to have a lower limit like 0.5 right.

return Padding(
  padding: EdgeInsets.only(
    top: sameUserAsNext ? 4.0 : 10.0,
    bottom: 4.0,
    left: 10.0,
    right: 10.0,
  ),
  child: Align(
    alignment: isCurrentUser ? Alignment.centerRight : Alignment.centerLeft,
    child: Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      decoration: BoxDecoration(
        color: isCurrentUser
            ? const Color.fromARGB(255, 68, 129, 235)
            : Colors.grey[800],
        borderRadius: BorderRadius.circular(25),
      ),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width * 0.7,
        ),
        child: Text(
          message.text,
          style: TextStyle(
            color: Colors.white,
            fontSize: messageFontSize,
            height: 1.4,
          ),
          overflow: TextOverflow.visible,
          softWrap: true,
          maxLines: null,
          textAlign: TextAlign.left,
        ),
      
                      ),
                    ),
                  ),
                );
              },
            ),
          ),


Solution

  • You can fix that by adding this property to your Text widget:

    textWidthBasis: TextWidthBasis.longestLine
    

    Your code should look something like this:

    Text(
              message.text,
              style: TextStyle(
                color: Colors.white,
                fontSize: messageFontSize,
                height: 1.4,
              ),
              overflow: TextOverflow.visible,
              softWrap: true,
              maxLines: null,
              textAlign: TextAlign.left,
              textWidthBasis: TextWidthBasis.longestLine,
            )
    

    So instead of having this:
    Without TextWidthBasis.longestLine

    It will look like this:
    With TextWidthBasis.longestLine

    Hope this help!