Flutter/Dart - Split Comma Separated String into 3 Variables?
10,412
Solution 1
You could use a Map
, which is better suited for variables with dynamic length :
final tagName = 'grubs, sheep';
final split = tagName.split(',');
final Map<int, String> values = {
for (int i = 0; i < split.length; i++)
i: split[i]
};
print(values); // {0: grubs, 1: sheep}
final value1 = values[0];
final value2 = values[1];
final value3 = values[2];
print(value1); // grubs
print(value2); // sheep
print(value3); // null
Solution 2
you can use a list and add items one by one
final names= 'first, second';
final splitNames= names.split(',');
List splitList;
for (int i = 0; i < split.length; i++){
splitList.add(splitNames[i]);
}
Author by
Meggy
I'm a self-taught novice stumbling like a drunk through php, javascript, mysql, drupal and flutter.
Updated on December 23, 2022Comments
-
Meggy over 1 year
I've got a comma-separated string of tags, IE "grubs, sheep, dog". How can I separate this into three variables? I tried ;
var splitag = tagname.split(","); var splitag1 = splitag[0]; var splitag2 = splitag[1]; var splitag3 = splitag[2];
But if any of the variables are null it throws an error. So I tried;
String splitagone = splitag1 ?? ""; String splitagtwo = splitag2 ?? ""; String splitagthree = splitag3 ?? "";
But I got the same error. So is there another way I can check that the tag is not null and use the variable?
if(tagname != null) { tagname.split(',').forEach((tag) { // something? }); }
-
Meggy over 3 yearsThat did it. Thanks!
-
adarsh about 2 yearsfinal names= 'first, second'; final splitNames= names.split(','); List splitList; for (int i = 0; i < splitNames.length; i++){ splitList.add(splitNames[i]); }