While using Flutters http
request library I was wondering if there was an easy way to check if a request was successful without having to check the status code.
Most code samples I saw (including official ones) do something like this:
http.Response response = await http.Client().get(...);
if (response.statusCode == 200) {
...
}
However, those examples are ignoring the fact that all HTTP status codes starting with 2XX
are considered successful. For example 201
stands for 201 Created
.
I know for a fact that pythons http
library has a simple ok
flag, so in python could do something like this:
if response.ok:
...
Is there a feature like this in flutter/dart or do I have to implement a manual check?
CodePudding user response:
You can make an extension method that does this easily:
extension IsOk on http.Response {
bool get ok {
return (statusCode ~/ 100) == 2;
}
}
By adding the extension above, you can use the same response response.ok
syntax that you like.
This extension works by isolating the 100th place digit by doing a truncating division by 100 and comparing the result to 2.