Search code examples
flutterdart

Dart. Instance of 'JSArray<dynamic>': type 'List<dynamic>' is not a subtype of type 'List<double>'


Trying to parse data from json to Map<double, double>, but stuck with this error

DartError: TypeError: Instance of 'JSArray': type 'List' is not a subtype of type 'List'

in the end i need 'data' as Map<double, double> but the problem remains no matter what methods i use.

Here is the simpliest code:

 final jsonData = await rootBundle.loadString('assets/data/dataTest.json');
    final data = json.decode(jsonData);
    final modules = data['modules'];
    final steps = modules['data'];
    print(steps);

    final List<double> keys =
        steps.keys.map((e) => double.parse(e)).toList();

The json example:

{
    "modules": {
        "name": "name1",
        "data": {
            "1": "450",
            "2": "26.8",
            "4": "12.4",
            "3.07": "14",
            "1.25": "79",
            "1.53": "47.5",
            "2.5": "18.8",
            "1.86": "30.2",
            "1.66": "43.2"
        }
    }
}

Solution

  • You can use Map.map() to convert from the Map<String, dynamic> to a Map<double, double> as follows:

      final steps = modules['data'] as Map<String, dynamic>; // let the compiler know what type of map it already is
    
      final result = steps.map<double, double>(
          (k, v) => MapEntry(double.parse(k), double.parse(v)));
    
      print(result.runtimeType); // Map<double, double>