Home > OS >  Convert the string inside of the list into list format (Flutter)
Convert the string inside of the list into list format (Flutter)

Time:11-03

How to regenerate whole list to convert string(list) inside of the list into list format

 List<Map<String, dynamic>> category = [
    {
      "name": "One",
      "detail": "['1', '1', '1', '1', '1', '1']"
    },
    {
      "name": "two",
      "detail": "['2', '2', '2', '2', '2', '2']"
    },
    {
      "name": "three",
      "detail": "['3', '3', '3', '3', '3', '3']"
    },
  ];


Become

 List<Map<String, dynamic>> category = [
    {
      "name": "One",
      "detail": ['1', '1', '1', '1', '1', '1']
    },
    {
      "name": "two",
      "detail": ['2', '2', '2', '2', '2', '2']
    },
    {
      "name": "three",
      "detail": ['3', '3', '3', '3', '3', '3']
    },
  ];

How to regenerate whole list to convert string(list) inside of the list into list format

CodePudding user response:

List<Map<String, dynamic>> category = [
    {
      "name": "One",
      "detail": "['1', '1', '1', '1', '1', '1']"
    },
    {
      "name": "two",
      "detail": "['2', '2', '2', '2', '2', '2']"
    },
    {
      "name": "three",
      "detail": "['3', '3', '3', '3', '3', '3']"
    },
  ];


for(var e in category){
    Map<String,dynamic> item = e;
    String s = e['detail'];
    s = s.substring(1,s.length-1);
    item['detail'] = s.split(',');
    result.add(item);
  }

print(result);

CodePudding user response:

There are more ways of doing this :

try running this example on dartpad

import 'dart:convert';

void main() {
  String ss = "['3', '3', '3', '3', '3', '3']";
  String a= ss.replaceAll('[','');
  String b= a.replaceAll(']','');
  String c= b.replaceAll("'",'');
  List result = c.split(',');
  print(result);
}

CodePudding user response:

for (var element in category) {
  element['detail'] =
      json.decode(element['detail'].toString().replaceAll("\'", "\""));
}
log("$category");
  • Related