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?
});
}
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
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With