Search code examples
stringflutterdartkeyvaluepair

how separate string into key/value pair in dart?


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]);
      
        
        }
}

Solution

  • 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];
        }
    }