Search code examples
flutterdartflutter-layout

Flutter align timestamp text on bubble chat message


My chat bubble looks like this:

enter image description here

I want its timestamp to stick to the right side like the following:

enter image description here

Here is my code:

   return Align(
      alignment: alignment,
      child: Bubble(
        margin: BubbleEdges.only(
          top: 10,
          left: leftMargin,
          right: rightMargin,
        ),
        color: backgroundColor,
        nip: bubbleNip,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            content,
            const SizedBox(height: 5),
            Text(timeFormat01(timestamp)),
          ],
        ),
      ),
    );

How do I do that?

What doesn't work?

Using Row mainAxisAlignment: MainAxisAlignment.end or Align alignment: Alignment.centerRight leads to stretching all bubbles to max width.

enter image description here

Adding crossAxisAlignment: CrossAxisAlignment.end to the Column will align all texts that are smaller than the timestamp text to the right side.

enter image description here


Solution

  • Using IntrinsicWidth and Align solved my issue.

    Here is the result:

    return Align(
          alignment: alignment,
          child: Bubble(
            margin: BubbleEdges.only(
              top: 10,
              left: leftMargin,
              right: rightMargin,
            ),
            color: backgroundColor,
            nip: bubbleNip,
            child: IntrinsicWidth( // <--- here
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  content,
                  const SizedBox(height: 5),
                  Align(
                    alignment: Alignment.centerRight, // <--- here
                    child: Text(timeFormat01(timestamp)),
                  ),
                ],
              ),
            ),
          ),
        );
    

    Read more about IntrinsicWidth use cases and documentation.

    Note:

    This class is relatively expensive. Avoid using it where possible.