Martin Zhu
Martin Zhu

Reputation: 431

How to make the size of the Text Widget change with the content in flutter?

I want to design a combined Text widget that consists of two Text widget.

The size of the first Text widget changes as the content changes, and when it reaches the maximum length, an ellipsis is displayed. Like below, the red line part is fixed.

Then this is my code:

Row(
  children: <Widget>[
    Expanded(
      child: Text(
        'W',
        overflow: TextOverflow.ellipsis,
      ),
    ),
    Text(
      '(0x1234…1234)',
      style: TextStyle(
        fontSize: 12,
        color: Colors.black,
      ),
    ),
  ],
);

When the length is the largest, the display is normal. But when the length is very small, there will be a blank in the middle.

So, how do I need to improve my code?

Upvotes: 1

Views: 1442

Answers (3)

ibhavikmakwana
ibhavikmakwana

Reputation: 10101

You need to use Flexible widget instead of the Expanded.

Row(
  children: <Widget>[
    Flexible(
      child: Text(
        'Was',
        overflow: TextOverflow.ellipsis,
      ),
    ),
    Text(
      '(0x1234…1234)',
      style: TextStyle(
        fontSize: 12,
        color: Colors.black,
      ),
    ),
  ],
),

Using a Flexible widget gives a child of a Row, Column, or Flex the flexibility to expand to fill the available space in the main axis.

While Expanded, forces the child to expand to fill the available space.

You can also pass the fit: FlexFit.tight [The child is forced to fill the available space] or fit: FlexFit.loose [The child can be at most as large as the available space (but is allowed to be smaller).] to Flexible widget.

By Default it is set to FlexFit.loose.

Upvotes: 4

Pablo Barrera
Pablo Barrera

Reputation: 10963

You should use Flexible instead of Expanded

Row(
  children: <Widget>[
    Flexible(
      child: Text(
        'W',
        overflow: TextOverflow.ellipsis,
      ),
    ),
    Text(
      '(0x1234…1234)',
      style: TextStyle(
        fontSize: 12,
        color: Colors.black,
      ),
    ),
  ],
)

Upvotes: 1

CopsOnRoad
CopsOnRoad

Reputation: 267454

Not sure if I got your question properly, do you want to remove the white space?

Row(
   children: <Widget>[
     Expanded(
       child: Align( // add this
         heightFactor: 1,
         alignment: Alignment.centerRight, // this is what you need
         child: Text(
           'W',
           overflow: TextOverflow.ellipsis,
         ),
       ),
     ),
     Text(
       '(0x1234…1234)',
       style: TextStyle(
         fontSize: 12,
         color: Colors.black,
       ),
     ),
   ],
 )

Upvotes: 0

Related Questions