5

How to convert such a Map:

Map<dynamic, dynamic> a = {2022-04-10: [8:00, 15:00]}; //No quotes

To obtain:

Map<String, List<String>> b = {"2022-04-10": ["8:00", "15:00"]};

I tried to do so, but it doesn't work for me. There is no error, but if you call print, nothing happens:

String str = '{2022-04-10: [8:00, 15:00]}';
final Map<dynamic, dynamic> dynamicMapFromJson = json.decode(str);
Map<String, List<String>> schedule = dynamicMapFromJson.cast<String, List<String>>();

I am teaching this Map from Firebase:

enter image description here

await FirebaseFirestore.instance
        .collection('call')
        .get()
        .then((QuerySnapshot querySnapshot) {
      for (var doc in querySnapshot.docs) {
        Map<String, List<String>> _schedule = doc.get('schedule');
      }
    });
6
  • Please provide more detailed information about what you want to do and your data. the code you shared gives syntax error. Commented Apr 10, 2022 at 19:17
  • @SalimBaskoy I have added the code to my question Commented Apr 10, 2022 at 19:41
  • @YeasinSheikh Friend, do you know how to do this? Commented Apr 10, 2022 at 20:10
  • Should it be like String str = '{"2022-04-10": ["8:00", "15:00"]}'; on response string? Commented Apr 10, 2022 at 20:19
  • @YeasinSheikh Yes it will fit Commented Apr 10, 2022 at 20:25

2 Answers 2

8

Your map is

Map<dynamic, dynamic> a = {"2022-04-10": ["8:00", "15:00"]};

you can convert it by two ways

Map<dynamic, dynamic> a = {"2022-04-10": ["8:00", "15:00"]};
Map<String, List<String>> converted = {};

// 1st way:
for (var item in a.keys)
  converted[item.toString()] = List<String>.from(a[item]);
 
// 2nd way:
for (var item in a.keys)
{
  List<String> _new = [];
  for (var newItem in List.from(a[item]))
     _new.add(newItem.toString());
  converted[item.toString()] = _new;
}
Sign up to request clarification or add additional context in comments.

2 Comments

the problem is that there are no quotes
i see, please try the second way, i think it will work (i've modified it)
-1

you can use the magic of regex "it's not really perfect expression" but it's working fine with your case here you can matches date yyyy-mm-dd and hh: mm then replace with quoted ones

String str = '{2022-04-10: [8:00, 15:00]}';

 var stringify =  str.replaceAllMapped(RegExp("([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{0,2}:[0-9]{0,2})"), (match) => "\"${match.group(0)}\""); 
 //This step just for replace ":" with normal :
 stringify = stringify.replaceAll("\":\"",":");
 print("value:  $stringify");

  
 final Map dynamicMapFromJson = json.decode(stringify);
 print(dynamicMapFromJson);

Try the code here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.