First of all, I am extremely new to working with HTTP Requests and stuff.
I jave created an API in Java Spring, and I have a bunch of Fitness Programmes assigned to a User, but this error will occur when I try to get the Object from the JSON in Flutter. I use the http and convert dart packages.
List is not a subtype of type 'Map<String,dynamic>
The problem is this line:
var userModel = Users.fromJson(jsonMap);
This is the getUsers Method:
Future<Users> getUsers() async{
var client = http.Client();
var userModel = null;
var response = await client.get(Uri.parse(Strings.users_url));
try {
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
print(jsonMap);
var userModel = Users.fromJson(jsonMap);
}
}
catch(Exception) {
print(Exception);
return userModel;
}
return userModel;
}
These are the Users and Fitness Programme classes:
// To parse this JSON data, do
//
// final users = usersFromJson(jsonString);
import 'dart:convert';
List<Users> usersFromJson(String str) => List<Users>.from(json.decode(str).map((x) => Users.fromJson(x)));
String usersToJson(List<Users> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Users{
Users({
this.id,
this.email,
this.password,
this.firstName,
this.lastName,
this.birthday,
this.weight,
this.height,
this.fitnessProgrammes,
});
int id;
String email;
String password;
String firstName;
String lastName;
dynamic birthday;
int weight;
int height;
List<FitnessProgramme> fitnessProgrammes;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"],
email: json["email"],
password: json["password"],
firstName: json["firstName"],
lastName: json["lastName"],
birthday: json["birthday"],
weight: json["weight"],
height: json["height"],
fitnessProgrammes: List<FitnessProgramme>.from(json["fitnessProgrammes"].map((x) => FitnessProgramme.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"email": email,
"password": password,
"firstName": firstName,
"lastName": lastName,
"birthday": birthday,
"weight": weight,
"height": height,
"fitnessProgrammes": List<dynamic>.from(fitnessProgrammes.map((x) => x.toJson())),
};
}
class FitnessProgramme {
FitnessProgramme({
this.id,
this.name,
this.trainingDifficulty,
});
int id;
String name;
String trainingDifficulty;
factory FitnessProgramme.fromJson(Map<String, dynamic> json) => FitnessProgramme(
id: json["id"],
name: json["name"],
trainingDifficulty: json["trainingDifficulty"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"trainingDifficulty": trainingDifficulty,
};
}
CodePudding user response:
Your API is probably returning an array of users instead of a single user. So the decoded JSON type is List<Map<String, dynamic>>
. To resolve this, either loop through each user and instantiate them or make your API return just one specific user.
This code below will probably work and instantiate the first user returned by the API:
var userModel = Users.fromJson(jsonMap[0]);