I'm sending the JSON as string from response.body, but getting "Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast" error after mapping in Flutter/Dart. If i write the JSON manually, the code works. But if i get the JSON as string from parameter, getting cast error.
I tried to cast return value to List but extractedData should change i guess, stucked here. "s" is JSON string.
The getVacDates function is for getting only date or total values from the JSON like [10/14/21, 10/15/21, 10/16/21...]
by mapping.
static List<String> getVacDates(String s) {
final newList = jsonEncode(s);
final extractedData = jsonDecode(newList) as Map<String, dynamic>;
final china= extractedData['timeline'].map((e) => e["date"]);
List<String> StringList = china.cast<String>();
print(StringList);
return StringList;
}
For information the JSON is:
{"country":"USA","timeline":
[{"total":409571117,"daily":757824,"totalPerHundred":121,"dailyPerMillion":2253,"date":"10/14/21"},
{"total":410559043,"daily":743873,"totalPerHundred":122,"dailyPerMillion":2212,"date":"10/15/21"},
{"total":411028977,"daily":737439,"totalPerHundred":122,"dailyPerMillion":2193,"date":"10/16/21"},
{"total":411287235,"daily":731383,"totalPerHundred":122,"dailyPerMillion":2175,"date":"10/17/21"}]}
Simplified program:
responseVac = await http.get('https://disease.sh/v3/covid-19/vaccine/coverage/countries/usa?lastdays=3');
var data = MyFile.myFunction(xxx, yyy, responseVac.body);
in MyFile:
static ChartsData myFunction(String xxx, bool yyy, String responseVac) {
List<String> getVacDates(String s) =>
[for (final data in jsonDecode(s)['timeline']) data['date'] as String];
print(getVacDates(responseVac));
CodePudding user response:
Not entire sure what you are trying to get but is it something like this?
import 'dart:convert';
void main() {
print(getVacDates(jsonString)); // [10/14/21, 10/15/21, 10/16/21, 10/17/21]
}
List<String> getVacDates(String s) => [
for (final timeline in jsonDecode(s)['timeline'])
timeline['date'] as String
];
const jsonString = '''{
"country": "USA",
"timeline": [
{
"total": 409571117,
"daily": 757824,
"totalPerHundred": 121,
"dailyPerMillion": 2253,
"date": "10/14/21"
},
{
"total": 410559043,
"daily": 743873,
"totalPerHundred": 122,
"dailyPerMillion": 2212,
"date": "10/15/21"
},
{
"total": 411028977,
"daily": 737439,
"totalPerHundred": 122,
"dailyPerMillion": 2193,
"date": "10/16/21"
},
{
"total": 411287235,
"daily": 731383,
"totalPerHundred": 122,
"dailyPerMillion": 2175,
"date": "10/17/21"
}
]
}''';