It is a obligatory passage for all developers, no one can skip it. Getting to know http requests and interfacing with web services is an essential part of many apps. The great thing is that, in Flutter, it’s all very simple to do.
We’ll look at a package in this article called, simply, http, which is published by the official Dart development team. All you need to do some networking is there and it’s really easy to use (as long as you know how to use async functions in Flutter, if not, check out the official dart documentation here).
Before starting we’ll need to add http as a dependency, so let’s edit our
pubspec.yaml file and add http:
Then we’ll just need to do a good old
flutter pub get and import it in our file. I will use as a test case an ideal API Wrapper in order to call a single function to do all the work for us:
We should also need to divide the URL endpoint from the eventual API in order to create the
Uri we need to call:
Let’s now start with the basics: GET requests!
A GET request is absolutely easy to do, first we need to create the
uri which contains the path and query:
then just use the http package to obtain a
Future<Response> which represent the result of the operation with data like body and status code:
The end. Great, ain’t it??!
POST, DELETE and PUT
Those three methods work similarly to GET but we expect to add some body parameters. Fear not gentle developer!
With the call we can add a String body with a jsonEncoded
Map<String,String> which will be body parameters: then we only need to use http package with
You can also jsonEncode objects as you wish, just remember to add the encoding type.
Now let’s start creating our API wrapper method, complete of switch-case for our enum methods:
As final touch let’s add the possibility to add custom headers to our API calls.
Add custom headers
Adding custom headers is just another Map to add to http methods:
Let’s now complete our API Wrapper adding headers to our callAPI function:
Well guys, that was pretty easy, ain’t it? http has many other features like, json body encoding or multi-part request but it is a bit out of scope from this article. Remember that you should not reinvent hot water, Dart team already did.