[Solved] Is it possible to build a list from a carriage return separated string?

Question

Asked by Mark on November 11, 2021 (source).

Background

I have the following string:

var MyString = 'Test1⏎Test2⏎Test3⏎Test4'

= line feed = \n

What I'm trying to do

  • I want to create a List which is a list of lines. Basically every item that is followed by a \n would become an entry in the list.
  • I want the base string MyString to become shortened to reflect what pieces of the string have been moved to the List
  • The reason I want to leave a residual MyString is that new data might come in later that might be considered part of the same line, so I do not want to commit the data to the List until there is a carriage return seen

What the result of all this would be

So in my above example, only Test1 Test2 Test3 are followed by \n but not Test4

Output List would be: [Test1, Test2, Test3]

MyString would become: Test4

What I've tried and failed with

I tried using LineSplitter but it seems to want to take Test4 as a separate entry as well

final lines = const LineSplitter().convert(MyString);
for (final daLine in lines) {
  MyList.add(daLine);
}

And it creates [Test1, Test2, Test3, Test4]

Answer

Question answered by Suporte01 (source).

A solution would be to just .removeLast() on the list that you split.

String text = 'Test1\nTest2\nTest3\nTest4';

List<String> list = text.split('\n');
text = list.removeLast();

print(list); // [Test1, Test2, Test3]
print(text); // Test4
DART FLUTTER
SHARE: