I need to download json data from the internet
[
{
"day": "Monday:",
"hours": [22, 27]
},
{
"day": "Tuesday :",
"hours": [22, 27]
},
{
"day": "Wednesday",
"hours": [22, 27]
},
]
I want the data from the "hours" item to be retrieved as separate elements (without square brackets)
Could someone please provide an example ?
I get an error popping up all the time
"flutter _typeerror (type 'string' is not a subtype of type 'map<dynamic, dynamic>'"
My current class looks like this
class DaysList {
final String days;
final String hours;
const DayList({required this.days, required this.hours});
static DaysList fromJson(json) => DaysList(
days: json['days'],
hours: json['hours'] ,
);
}
This returns all data with "hours" but in square brackets
CodePudding user response:
In your response,key 'hours' is a list of integers. So you need specify the data type as List in your class data members.
class DaysList {
DaysList({
this.day,
this.hours,
});
String day;
List<int> hours;
factory DaysList.fromJson(Map<String, dynamic> json) => DaysList(
day: json["day"],
hours: List<int>.from(json["hours"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"day": day,
"hours": List<dynamic>.from(hours.map((x) => x)),
};
}
CodePudding user response:
Future<List<DaysList>> daysFuture = getDay();
Future<List<DaysList>> getDay() async {
const url = 'address of my website';
final response = await http.get(Uri.parse(url));
final body = json.decode(response.body);
return json.decode(response.body);
}
class DaysList {
DaysList({
this.day,
this.hours,
});
String day;
List<int> hours;
factory DaysList.fromJson(Map<String, dynamic> json) => DaysList(
day: json["day"],
hours: List<int>.from(json["hours"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"day": day,
"hours": List<dynamic>.from(hours.map((x) => x)),
};
Thank You for Your quick reply
if I put that code to VS and runs app I have feedback " _TypeError (type 'List' is not a subtype of type 'FutureOr<List>')"