skip to Main Content

i have this

String stringArray = "[folder/1.png,folder/2.png,folder/3.png]";

this is what i want

List array = ["folder/1.png","folder/2.png","folder/3.png"]

converting to this

List array = ["folder/1.png","folder/2.png","folder/3.png"]

3

Answers


    1. Split the String like stringArray.split(",");
    2. Map them like this stringArray.map((file) => file.replaceAll("[", "").replaceAll("]",""));
    Login or Signup to reply.
  1. Lets say you have this:

    String stringArray = "[folder/1.png,folder/2.png,folder/3.png]";
    

    You can parse it with jsonDecode method, like this:

    String stringArray = "[folder/1.png,folder/2.png,folder/3.png]";
    var newStr = stringArray
        .replaceAll("[", '["')
        .replaceAll(",", '","')
        .replaceAll("]", '"]');
    
    var converted = json.decode(newStr).cast<String>().toList();
    

    your result would be:

    //["folder/1.png","folder/2.png","folder/3.png"]
    
    Login or Signup to reply.
  2. Try the following simple code snippet:

    void main() {
      String stringArray = "[folder/1.png,folder/2.png,folder/3.png]";
    
      stringArray = stringArray.replaceAll('[', '');
      stringArray = stringArray.replaceAll(']', '');
    
      var s = stringArray.split(',');
      List<String> newStringArray = [];
    
      for (var e in s) {
        newStringArray.add(e);
      }
      print(newStringArray);
    }
    

    It’s now converted to List<String> and here’s the output:

    [folder/1.png, folder/2.png, folder/3.png]

    Note: IDEs ignore the quotation marks, usually not displayed.

    If you really want to surround that string with quotes replace the above for loop to that :

      for (var e in s) {
        var first = '"';
        var last = '"';
        e = first + e + last;
        newStringArray.add(e);
      }
    

    Here’s the output:

    ["folder/1.png", "folder/2.png", "folder/3.png"]

    Hope it helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search