Home > OS >  Dart convert Map<dynamic, dynamic> to Map<String, List<String>>
Dart convert Map<dynamic, dynamic> to Map<String, List<String>>

Time:04-11

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

CodePudding user response:

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