This happens after fetching data from an api.
The request executes successfully and i get a json response of departments but I can’t process the response. Uncaught (in promise) Error: Expected a value of type ‘String’, but got one of type ‘TypeErrorImpl’
The json response object
{
"success": true,
"data": [
{
"id": "56c8b5f8-7f74-4f0c-9fc0-9a3c411bc3a4",
"image": "http://127.0.0.1:8000/media/api/uploads/departments/2023/03/14/child_yk4u2KO.png",
"name": "Education And Child Development",
"slug": "education-and-child-development",
"created_at": "2023-02-23T14:51:39Z",
"updated_at": "2023-03-14T14:24:10.699998Z"
}
],
"message": "Departments successfuly retrieved"
}
The department.dart file
class Department {
String id;
String image;
String name;
String slug;
Department({
this.id,
this.image,
this.name,
this.slug,
});
Department.fromJson(Map<String, dynamic> json) {
id = json['id'].toString();
image = json['image'] != null ? json['image'] : null;
name = json['name'] != null ? json['name'] : null;
slug = json['slug'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['image'] = this.image;
data['name'] = this.name;
data['slug'] = this.slug;
return data;
}
}
The function fetching the data
Future<Stream<Department>> getSchoolDepartments() async {
final String url =
'${GlobalConfiguration().getString('api_base_url')}departments';
final client = new http.Client();
try {
final streamedRest = await client.send(http.Request('get', Uri.parse(url)));
print("Status code : " + streamedRest.statusCode.toString());
return streamedRest.stream
.transform(utf8.decoder)
.transform(json.decoder)
.map((data) => Helper.getData(data))
.expand((data) => (data as List))
.map((data) {
print("data : " + data);
return Department.fromJson(data);
});
} on Exception catch (e) {
print(e);
}
}
The processing function in school_controller.dart
void listenForDepartments() async {
print("starting departments stream");
final Stream<Department> stream = await getSchoolDepartments();
stream.listen((Department _department) {
setState(() => departments.add(_department));
}, onError: (a) {
print("Failed to add department : " + a);
}, onDone: () {});
}
I am expecting a successfull processing with departments object populated with data from json response.
2
Answers
The error actually comes from calling the methods below
1. print("data : " + data); Must be print("data : $data");
2. print("Failed to add department : " + a); Must be print("Failed to add department : $a");
These don’t make much sense:
it’s literally the same as
You’d probably want to do
Or make those fields nullable.