I updated my flutter to 2.10 and my Dio suddenly starts giving me this error from the code below:
static Future getRequest(String url, queryParam) async { List data = [];
SharedPreferences crypt = await SharedPreferences.getInstance();
String? auth = crypt.getString("access");
try {
var res = await dio.get(url,
queryParameters: queryParam,
options: Options(headers: {
"accept": "application/json",
// "Authorization": "Bearer $auth"
}));
if (res.statusCode >= 200 && res.statusCode <= 250) {
print("RESPONSE");
print(res.data);
print(res.data);
data.add({"status": "success", "message": res.data});
return data;
} else {
data.add({"status": "failed", "message": res.data});
return data;
}
}on DioError catch (e) {
if (e.response.statusCode >= 400 && e.response.statusCode <= 450) {
data.add({
"status": "failed",
"message": e.response.data["error"]["message"]
});
return data;
}
}
}
}
I get the following errors:
Error: Operator '>=' cannot be called on 'int?' because it is potentially null.
if (res.statusCode >= 200 && res.statusCode <= 250) {
and also:
Error: Operator '>=' cannot be called on 'int?' because it is potentially null.
if (e.response.statusCode >= 400 && e.response.statusCode <= 450) {
Any Idea on how to solve this?
CodePudding user response:
This is part of sound null safety https://dart.dev/null-safety, it means that your status code can be null and null values can't be compared with operators (you can just check if they are not null)
you have several options to overcome this
force not null: In this case, you check if your status code is not null beforehand and force the not null value
if(res.statusCode != null) {
// do your check
} else {
//you don't have a statusCode, react accordlying
}
depending on your structure you may need to add a !
after your variable in order to make the compiler understand that you know the variable is not null
if(res.statusCode != null) {
// use of res.statusCode! may be needed in relation to where your check is placed
} else {
//you don't have a statusCode, react accordlying
}
Another option is to use the null safe operator ??
this tells the compiler what to do in case of a null value
final statusCode = res.statusCode? ?? -1;
This behave as "if res.statusCode is not null, assign the value, otherwise assign -1" then you are free to use the new statusCode
as you did before null safety, since now, the statusCode
value can't be null anymore
CodePudding user response:
It' a null safety error, change:
var res = await dio.get(url,
queryParameters: queryParam,
options: Options(headers: {
"accept": "application/json",
// "Authorization": "Bearer $auth"
}));
to:
var res = await dio.get(url,
queryParameters: queryParam,
options: Options(headers: {
"accept": "application/json",
// "Authorization": "Bearer $auth"
})) ?? 0;
This will adding a default value to res in case it will be null and error will disapear.