-1

how can a string be separated into key/value pair in dart? The string is separated by a "=". And how can the pair value be extracted?

    main(){
  
  var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];

Map<String ,dynamic> map = {};
    for (String s in stringTobeSeparated) {
          var keyValue = s.split("=");
    //failed to add to a map , to many positiona arguments error
         map.addAll(keyValue[0],keyValue[1]);
      
        
        }
}
Mala
  • 89
  • 9

2 Answers2

1

The split() function gives you a List of Strings, so you just need to check if the length of this List is equal to 2 and then you can add those values in a Map like this:

Map<String, String> map = {};
for (String s in stringTobeSeparated) {
    var list = s.split("=");
    if(list.length == 2) {
        // list[0] is your key and list[1] is your value
        map[list[0]] = list[1];
    }
}
Ruben Röhner
  • 593
  • 4
  • 16
0

You can use map for this, the accepted answer is correct, but since your string looks like this

var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];

I would rather use regex to remove spaces from final result (replace the line with split with this):

var list = s.split(RegExp(r"\s+=\s+"));
galloper
  • 813
  • 1
  • 9
  • 17