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

Viewed 16813

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?    
      });
    }
4 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

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 want just want to check if tagname is null just use tagname?.split(). But then when you get the values you will have to do this as well because otherwise you'll get a null exception splitTag?[] ?? "" The ?? is optional if you want to return a blank string instead of null.

Clean up the string splits before using them:

final names= 'first, second, 3';
values = names.split(",").map((x) => x.trim())).where((element) => element.isNotEmpty).toList()

final value1 = values[0];
final value2 = values[1];
final value3 = values[2];
Related