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

9

33

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?

Maulstick answered 18/11, 2018 at 8:32 Comment(0)
L
43

You could do something like this:

String truncateWithEllipsis(int cutoff, String myString) {
  return (myString.length <= cutoff)
    ? myString
    : '${myString.substring(0, cutoff)}...';
}
Logicize answered 17/5, 2019 at 13:24 Comment(0)
K
20

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));
}
Killy answered 30/3, 2020 at 11:21 Comment(2)
This doesn't work when string length is less than maxCharsOpalina
You are right. Therefore you must be check string length first.Killy
H
15

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);
}
Hofmann answered 18/11, 2018 at 15:14 Comment(2)
it's a dart question, not a flutter!Maryettamaryjane
Check the added pure Dart code, thanks for your comment , I think I was in flutter overdose when I wrote the original answer :)Hofmann
O
15

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...
Oneupmanship answered 7/7, 2020 at 6:45 Comment(0)
E
5

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)
Einstein answered 30/12, 2020 at 15:31 Comment(0)
M
3

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;
}

Mujik answered 18/3, 2021 at 9:23 Comment(0)
S
3

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...

Selhorst answered 29/8, 2021 at 13:11 Comment(0)
J
0

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;
}
Jeffreys answered 15/12, 2022 at 17:3 Comment(0)
O
0

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,
  ),
)
Oxbridge answered 4/6 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.