This error is similar to another I’ve seen, but I’m not an experience Flutter developer. I receive and print in the console the response.body. I change some code, and covert to <String, dynamic>, but then I get an error in my Provider, and when I try to write return ref.read(profileProvider) when I write the dot, the function of the Api class does not appear.
I have this Class Below:
class Profile {
String status;
String message;
final Data data;
Profile({
required this.status,
required this.message,
required this.data,
});
factory Profile.fromJson(Map<String, dynamic> json) {
return Profile(
status: json['status'],
message: json['message'],
data: Data.fromJson(json['data']),
);
}
}
class Data {
String firstName;
String middleName;
String lastName;
String email;
String mobile;
String picture;
Data({
required this.firstName,
required this.middleName,
required this.lastName,
required this.email,
required this.mobile,
required this.picture,
});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
firstName: json['first_name'] ?? 'First Name Json',
middleName: json['middle_name'] ?? 'Middle Name',
lastName: json['last_name'] ?? 'Last Name',
email: json['email'] ?? 'Your email',
mobile: json['mobile'] ?? '999-999-9999',
picture: json['picture'] ?? 'assets/profile-image-holder.png',
);
}
}
My Api Call
class UserProfileService {
Future<Profile> getProfileInfo() async {
String? authToken = await readBearer();
//debugPrint(authToken);
final headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": 'Bearer $authToken!',
};
try {
final response = await http.get(
Uri.parse(ApiConstants.baseUrl + ApiConstants.userProfileInfo),
headers: headers,
);
if (response.statusCode == 200) {
//debugPrint((response.body));
//final profileResponse = Profile.fromJson(jsonDecode(response.body));
final profileResponse = jsonDecode(response.body);
debugPrint(profileResponse.toString());
return profileResponse;
} else {
return Profile.fromJson(jsonDecode(response.body));
}
} catch (error) {
// Handle any exceptions that occur during the request
return throw (Exception(error));
}
}
}
And finally, I’m using Riverpod in my Flutter project.
final profileProvider =
Provider<UserProfileService>((ref) => UserProfileService());
final profileDataProvider = FutureProvider<Profile>((ref) {
return ref.read(profileProvider).getProfileInfo();
});
Thanks for any help, I really appreciate it!
2
Answers
I was able to get the data from the Api by generating the class with https://app.quicktype.io, I knew there was something wrong with the clase I manually made, but I can't tell where the error is.
You need to return
Profile
instanceTry to convert it to async method and await