Wordwrap function for wrapping string in dart

459

Solution 1

This is Dart code for wrapping long string. It breaks long words as well.

void main() {
  String string = "Comments, notes or other information about the packages will print here. Your comments go here.";

  List<String> list = _wrapLine(string, 12);

  for (String str in list)
    print(str);
}

///
/// Wrap your string.
/// @param line - String line which need to be wrapped.
/// @param wrapLength - Wrapping threshold. Must be greater than 1.
/// @return
///
List<String> _wrapLine(String line, int wrapLength) {
  List<String> resultList = [];

  if (line == null || line.length == 0) {
    resultList.add("");
    return resultList;
  }
  if (line.length <= wrapLength) {
    resultList.add(line);
    return resultList;
  }

  List<String> words = line.split(" ");

  for (String word in words) {
    if (resultList.length == 0) {
      addNewWord(resultList, word, wrapLength);
    } else {
      String lastLine = resultList.last;

      if (lastLine.length + word.length < wrapLength) {
        lastLine = lastLine + word + " ";
        resultList.last = lastLine;
      } else if (lastLine.length + word.length == wrapLength) {
        lastLine = lastLine + word;
        resultList.last = lastLine;
      } else {
        if (_isThereMuchSpace(lastLine, wrapLength.toDouble())) {
          _breakLongWord(resultList, word, wrapLength, lastLine.length);
        } else {
          addNewWord(resultList, word, wrapLength);
        }
      }
    }
  }

  return resultList;
}

void addNewWord(List<String> resultList, String word, int wrapLength) {
    if (word.length < wrapLength) {
        resultList.add(word + " ");
    } else if (word.length == wrapLength) {
        resultList.add(word);
    } else {
        _breakLongWord(resultList, word, wrapLength, 0);
    }
}

void _breakLongWord(List<String> resultList, String word, int wrapLength, int offset) {
    String part = word.substring(0, (wrapLength - offset) - 1);
    if (offset > 1) {
        String lastLine = resultList.last;
        lastLine = lastLine + part + "-";
        resultList.last = lastLine;
    } else {
        resultList.add(part + "-");
    }

    String nextPart = word.substring((wrapLength - offset) - 1, word.length);
    if (nextPart.length > wrapLength)
        _breakLongWord(resultList, nextPart, wrapLength, 0);
    else if (nextPart.length == wrapLength)
        resultList.add(nextPart);
    else
        resultList.add(nextPart + " ");
}

bool _isThereMuchSpace(String line, double lineLength) {
  double expectedPercent = (lineLength * 65) / 100;
  if (line.length <= expectedPercent) return true;
  return false;
}

Solution 2

Add package basic_utils

Use this function StringUtils.addCharAtPosition():

e.g.

String s = 'An example of a long word is: Supercalifragulistic';
//This will add '\n' after every 10 positions.
print(StringUtils.addCharAtPosition(s, '\n',12,repeat:true));
/*
Output:
An example o
f a long wor
d is: Superc
alifragulist
ic
*/

Solution 3

I have tested this using only one example, please do test more.

void main() {
  int wrapLength = 15;
  String inputText = 'An example of a long word is: Supercalifragulistic';
  String outputText = wrapText(inputText, wrapLength);
  print(outputText);
}

String wrapText(String inputText, int wrapLength){
  List<String> separatedWords = inputText.split(' ');
  StringBuffer intermidiateText = StringBuffer();
  StringBuffer outputText = StringBuffer();
  
  for(String word in separatedWords){
    
    if((intermidiateText.length + word.length) >= wrapLength){
      intermidiateText.write('\n'); 
      outputText.write(intermidiateText);
      intermidiateText.clear();
      intermidiateText.write('$word ');
    } else {
      intermidiateText.write('$word ');
    }
    
  }
  
  outputText.write(intermidiateText); //Write any remaining word at the end
  intermidiateText.clear();
  return outputText.toString().trim();
}

Output:

An example of 
a long word 
is: 
Supercalifragulistic 

There would be much simpler and efficient ways to do the same but this crude version works.

Also came across this implementation detail of php version of the wordwrap method that uses regex. If anyone can convert to dart it would be much better than above solution.

Share:
459
Sachin Chavan
Author by

Sachin Chavan

Primarily MS shop. Currently working on .Net and Android. Like to learn and implement new technologies

Updated on December 22, 2022

Comments

  • Sachin Chavan
    Sachin Chavan over 1 year

    NOTE: I am not asking about wrapping string in text widget.

    Is there any word wrap function to word wrap a large string in dart. Builtin or via package

    e.g. 
    var str = "An example of a long word is: Supercalifragulistic";
    print(wordwrap(str,15,"\n");
    Output:
    An example of a \nlong word is: \nSupercalifragulistic 
    

    Like this one available in PHP : wordwrap()

  • Sachin Chavan
    Sachin Chavan almost 4 years
    +1 Thanks for the suggestion. But this will add \n at every X character, whereas I want something which respects WORD.