Tayo.dev
Tayo.dev

Reputation: 1656

Dart: How to Truncate String and add Ellipsis after character number

I'd like to add Ellipsis to a string after a certain character length and if the string length is not up to the character preset character length, the ellipsis (...) Should NOT be added.

How do i achieve this in Dart Language?

Upvotes: 33

Views: 24323

Answers (9)

Felipe D
Felipe D

Reputation: 1

If you are using Dart in Flutter you can use overflow: TextOverflow.ellipsis and also the Expanded() widget to avoid breaking the layout, leaving it this way.

Expanded(
  child: Text(
     'a very large text that will be added ellipsis at the end without breaking the layout of the app',
      style: YourStyleHere,
      overflow: TextOverflow.ellipsis,
  ),
)

Upvotes: 0

Alexander Kokin
Alexander Kokin

Reputation: 111

The problem with all the suggested solutions is that they truncate the string to fit the given size of the string. But when we actually get the problem of a string that is too long? Yes, this happens when the external component is too small for our string. All suggested solutions will cut the string even if there is enough space for it, for example, on wingow size changing on desktop. I solved this problem exactly depending on the size of the component on which the string is displayed in java a few years ago, but I haven't found a solution in Flutter yet.

I found :-)

    String truncate(String text, TextStyle style, double parentComponentLength) {
    String postfix = '...';
    var size = _calcTextSize(text, style);
    if (size.width < parentComponentLength) {
      return text;
    }
    while (size.width > parentComponentLength) {
      text = text.substring(0, text.length - 1);
      size = _calcTextSize('$text$postfix', style);
    }
    return '$text$postfix';
  }

  Size _calcTextSize(String text, TextStyle style) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
      textScaleFactor: WidgetsBinding.instance.window.textScaleFactor,
    )..layout();
    return textPainter.size;
}

Upvotes: 0

Saed Nabil
Saed Nabil

Reputation: 6871

wrap your Text widget with a container like below

Please : read the commented lines in the code below

class TruncatedText extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(),

    body: Container(
      //Here you can control the width of your container ..
      //when text exceeds it will be trancated via elipses...
      width: 130.0,
      child: Text('I have a trancated text',
        style: TextStyle(fontSize: 20),

        softWrap: false,
        overflow: TextOverflow.ellipsis,
      ),
    ),
  );
}  
}

Edit:

you can use this pure dart code as the original solution works for Flutter

void main() {
  String to_be_truncated = "Dart is excellent but flutter is awesome";
  int truncateAt = to_be_truncated.length-1;//if you use to_be_truncated.lengh no truncation will happen
  String elepsis = "..."; //define your variable truncation elipsis here 
  String truncated ="";
  
  if(to_be_truncated.length > truncateAt){
     truncated = to_be_truncated.substring(0,truncateAt-elepsis.length)+elepsis; 
  }else{
    truncated = to_be_truncated;
  } 
   print(truncated);
}

Upvotes: 15

Murat Ersin
Murat Ersin

Reputation: 438

You can use replaceRange method for this.

replaceRange

  var text = 'Hello World!';
  var r = text.replaceRange(7, text.length, '...');
  print(r); // -> Hello W...

Here is a complete example:

String truncate(String text, { length: 7, omission: '...' }) {
  if (length >= text.length) {
    return text;
  }
  return text.replaceRange(length, text.length, omission);
}

void main() {
  print(truncate('Hello, World!', length: 4));
}

Upvotes: 21

awaik
awaik

Reputation: 12335

One more example without cutting words.

/// truncate the [String] without cutting words. The length is calculated with the suffix.
extension Truncate on String {
  String truncate({required int max, String suffix = ''}) {
    return length < max
        ? this
        : '${substring(0, substring(0, max - suffix.length).lastIndexOf(" "))}$suffix';
  }
}

An example how to use

print('hello world two times!'.truncate(max: 15, suffix: '...'));

the result is hello world...

Upvotes: 3

Adam Smaka
Adam Smaka

Reputation: 6393

You can use Extension on a String:

extension StringExtension on String {
  String truncateTo(int maxLength) =>
      (this.length <= maxLength) ? this : '${this.substring(0, maxLength)}...';
}

Then

'My Very Long Text'.truncateTo(7); // My Very...

Upvotes: 16

mr_mmmmore
mr_mmmmore

Reputation: 2213

The following method builds on previous answers with these advantages:

  • Uses an extension on String
  • Works even if the string to truncate is shorter than the limit (no range errors)
  • Uses a single-char default ellipsis (i.e. “…”)
  • Takes the ellipsis into account when determining how much to truncate, ensuring the ellipsis doesn't make the string finally exceed the max length.

extension StringExtension on String {
  /// Truncate a string if it's longer than [maxLength] and add an [ellipsis].
  String truncate(int maxLength, [String ellipsis = "…"]) => length > maxLength
      ? '${substring(0, maxLength - ellipsis.length)}$ellipsis'
      : this;
}

Upvotes: 3

Hiran Walawage
Hiran Walawage

Reputation: 2185

Create extensions.dart file.

String truncateString(String data, int length) {
  return (data.length >= length) ? '${data.substring(0, length)}...' : data;
}

Use this as custom extension.

Usage

import 'package:project/util/extensions.dart';

truncateString('Sam Trio', 5)

Upvotes: 5

Nick
Nick

Reputation: 1215

You could do something like this:

String truncateWithEllipsis(int cutoff, String myString) {
  return (myString.length <= cutoff)
    ? myString
    : '${myString.substring(0, cutoff)}...';
}

Upvotes: 44

Related Questions