APIs and Flutter
Learning objectives
- You know how to use an API in a Flutter application.
Using APIs in an application, when they are encapsulated to a separate service, is straightforward. Here, we'll look into two distinct approaches that share the same underlying idea -- we create a stateful widget that shows the data retrieved from the API once the data is available.
Quick peek into nullable objects
As discussed in Sound null safety, Dart is a null safe language.
In the following approaches, we rely on a nullable object. By nullable, we mean that the object can hold a value null
-- by this, we indicate that there is no joke yet. In Dart, nullable objects are marked with a question mark ?
, e.g.
Joke? _joke;
To use properties of an object that has been set as nullable, we have to explicitly state that we know that the variable is not null, which is done with an exclamation mark !
, e.g.
Joke? _joke;
_joke = Joke("Why can't a bicycle stand up?", "It is two tired.");
print(_joke!.setup);
print(_joke!.punchline);
API in an application
To show contents retrieved from an API, we create a stateful widget that holds a property that we wish to show, and where the shown content may change. The following example outlines one implementation for such a stateful widget for showing and retrieving jokes, building on the JokeService
from the last part.
At the beginning, the value for _joke
can be null
; at this point, the user is shown the text Click the button..
. Clicking the button leads to the function getJoke
being called, which first retrieves a joke from the JokeService
and then sets the value of _joke
. Setting the value for _joke
is done using setState
, which sends a notification of a state change.
Altogether, an application for displaying jokes from an API could look as follows.
RiverPod and APIs
The same functionality could be implemented also with Riverpod, where the Joke would be stored within a provider. For simplicity, in the example below, we initiate the state with an empty Joke.