Home > Net >  How to split words in textfield
How to split words in textfield

Time:01-09

I want to get the inputs in the textfield as the user types. I use onChanged property of the textfield, then split the values as user types, but I only want to split 2 words per sentence.

What I want to achieve

Split only 2 words after user types more than 2 words.

See sample below

var value = "Split two words per sentence in the textfield"
// Split two
// words per
// sentence in
// the textfield

What I have tried

onChanged(String value) {
    final sentences = value.split(' ');
    for(var sentence in sentences) {
        print(sentence); //Split //two //words //per //sentence //in //the //textfield
     }
  }

Unfortunately my solution only splits the words by one. I wanted it to split per two words.

CodePudding user response:

I looks like that your onChanged function does not capture the 2 words argument that you need.

Try:

onChanged(String value) {
  final sentences = value.split(' ');
  for (int i = 0; i < sentences.length; i  = 2) {
    print(sentences[i]   ' '   sentences[i   1]);
  }
}

CodePudding user response:

.take(2) method to take the first two elements of the list returned by .split(' ') and then create a new list with those elements.you can then use the .skip(2) method to remove the first two elements from the original list, and like that..

onChanged(String value) {
List<String> sentences = value.split(' ');
while (sentences.isNotEmpty) {
print(sentences.take(2).join(' '));
sentences = sentences.skip(2).toList();
 }
}
  • Related