I am returning a data from an API using flutter and I have a problem telling me that
The body might complete normally, causing 'null' to be returned, but the
return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
This is my method:
Future<void> getDoctorsFromApi() async {
List<int> ids = await findAllDoctor().then((list) {
return list.map((e) => e.syncedId).toList();
});
doctors = await DoctorApi.getDoctors(ids).then((response) { // this is the line where error occurs
if (response.statusCode == 200) {
Iterable list = json.decode(response.body);
return list.map((model) => Doctor.fromJson(model)).toList();
} else {
_showMyDialog();
}
});
setState(() {
insertDoctors(database!);
});
}
CodePudding user response:
What will be the value of doctors
if response.statusCode
is not 200? Handle that
by creating a nullable local variable:
final List<Doctor>? result = await DoctorApi.getDoctors(ids).then((response) {
if (response.statusCode == 200) {
Iterable list = json.decode(response.body);
return list.map((model) => Doctor.fromJson(model)).toList();
}
return null;
});
if (result == null) {
_showMyDialog();
} else {
doctors = result;
setState(() => insertDoctors(database!));
}
CodePudding user response:
Just add some return or throw statement at the end of your function.
setState(() {
insertDoctors(database!);
});
throw ''; # or return something
}