Flutter text max lines

Flutter Text Max Lines

The Text widget in Flutter allows you to display a simple piece of text on the screen. By default, it automatically wraps the text if it exceeds the available width. However, you can limit the number of lines displayed using the maxLines property.

Here’s an example of how to use maxLines in a Text widget:

    
      Text(
        'This is a long text that needs to be wrapped if it exceeds the available space.',
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
    
  

In the above example, the text will be displayed on a maximum of two lines. If the text exceeds the available width, it will be truncated and an ellipsis (…) will be shown at the end of the second line.

The overflow property is used to define what should happen when the text overflows the specified number of lines. In this case, we used TextOverflow.ellipsis to show an ellipsis when the text is truncated.

You can also set maxLines to null for an unlimited number of lines or a specific number to limit it further.

    
      Text(
        'This text will be displayed on a single line.',
        maxLines: 1, // Only one line will be shown
        overflow: TextOverflow.ellipsis,
      ),
    
  

In the above example, the text will be displayed on a single line since maxLines is set to 1.

This is how you can use the maxLines property in Flutter’s Text widget to limit the number of lines for displaying text.

Leave a comment