Search code examples
flutterflutter-layout

How to align two Text widgets in Flutter


I have two Text widgets in a Row widget. One contains a label which can differ in length depending on user's language. Second one is a countdown timer that does not differ much in length (3 to 5 characters). E.g. ":05" or "12:34".

I want the timer to be displayed in full and the label to take the remaining space and be truncated if it cannot fit.

I tried something like this (in reality I am using more widgets for localization, semantics and managing font size based on screen dp, but I guess this is the gist of it...)

Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
          Text('Potentially long text here want to truncate it if there is not enough room',
                  overflow: TextOverflow.ellipses,
              ), 
          Text('12:34'),
      ],
)

This does not work and the first widget is displayed in full (in my case it actually fits), and the clock is pushed out of the screen causing a UI overflow.

What I want is something like this:

Potentially long text... 12:34

How can this be done?


Solution

  • Try Below code: wrap your Text inside Expanded or Flexible widget

       Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: const [
                  Expanded(
                    child: Text(
                      'Potentially long text here want to truncate it if there is not enough room',
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                  Spacer(),
                  Text('12:34'),
                ],
              ),