How to Convert String Values From Map<String, List<String>> to type Double? Flutter

392
void main() {
  Map<String, List<dynamic>> myMap = {
    'A': ['A', 'B', 'C'],
    '1': ['1', '2', '3'],
    '2': ['4', '5', '6']
  };

  myMap.forEach((key, value) {
    List<double> list = [];
    if (isNumeric(key)) {
      myMap[key].forEach((value) {
        list.add(double.parse(value));
      });
      myMap[key] = list;
    }
  });

  print(myMap);
  
}
//check if string value is numeric
bool isNumeric(String s) {
  if (s == null) {
    return false;
  }
  return double.parse(s, (e) => null) != null;
}

OUTPUT :

{A: [A, B, C], 1: [1.0, 2.0, 3.0], 2: [4.0, 5.0, 6.0]}
Share:
392
CuriousCoder
Author by

CuriousCoder

Updated on November 28, 2022

Comments

  • CuriousCoder
    CuriousCoder over 1 year

    I have

    Map<String, List<String>> myMap = {'A': ['A','B','C'], '1': ['1','2','3'], '2': ['4','5','6'] };
    

    I would like to convert the numerical values in Lists '1' and '2' from String to type Double. This is what I want to achieve:

    Map<String, List<String>> myMap = {'A': ['A','B','C'], '1': [1.00, 2.00, 3.00], '2': [4.00, 5.00, 6.00] };
    
    • Lucadmin
      Lucadmin over 3 years
      I don't think this is gonna work. You set the List type to String. Therefor, you cannot store Strings in it. A workaround would be to make a different map for the double-lists
    • CuriousCoder
      CuriousCoder over 3 years
      Ahhh you're right, thank you for pointing that out!