Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart - Split Comma Separated String into 3 Variables?

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?    
      });
    }
like image 755
Meggy Avatar asked Feb 18 '26 12:02

Meggy


2 Answers

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
like image 165
Augustin R Avatar answered Feb 21 '26 14:02

Augustin R


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]);
}
like image 44
Niaz Muhammad Avatar answered Feb 21 '26 13:02

Niaz Muhammad