MElochukwu
MElochukwu

Reputation: 51

How to split words in textfield

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.

Upvotes: 1

Views: 613

Answers (2)

Bilal Almefleh
Bilal Almefleh

Reputation: 376

.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();
 }
}

Upvotes: 1

originn
originn

Reputation: 13

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

Upvotes: 1

Related Questions