Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart List count showing one when splitting an empty string

Tags:

list

dart

I'm trying to do a basic grab from a Text Column in sqlite and processing it to a field in a model that is a List<String>. If data is empty then I want to set it as an empty list []. However, when I do this for some reason I get a list that looks empty but really with a length of 1. To recreate this issue I simplified the issue with the following.

String stringList = '';
List<String> aList = [];
aList = stringList.split(',');
print(aList.length);

Why does this print 1? Shouldn't it return 0 since there are no values with a comma in it?

like image 731
ZeroNine Avatar asked Oct 25 '25 00:10

ZeroNine


2 Answers

This should print 1.

When you split a string on commas, you are finding all the positions of commas in the string, then returning a list of the strings around those. That includes strings before the first comman and after the last comma. In the case where the input contains no commas, you still find the initial string.

If your example had been:

String input = "451";
List<String> parts = input.split(",");
prtin(parts.length);

you would probably expect parts to be the list ["451"]. That is also what happens here because the split function doesn't distinguish empty parts from non-empty.

If a string does contain a comma, say the string ",", you get two parts when splitting, in this case two empty parts. In general, you get n+1 parts for a string containing n matches of the split pattern.

like image 112
lrn Avatar answered Oct 26 '25 21:10

lrn


If you want to exclude empty parts from the result of a split (including if the empty string itself is split), you can always do something like:

final parts = input.split(',').where((e) => e.isNotEmpty).toList();

If input == '', the result will be [].

like image 23
Luke Hutchison Avatar answered Oct 26 '25 19:10

Luke Hutchison