Flutter for Jobseekers

Working with APIs and Asynchronous Operations

Futures and async/await, requesting and sending data with the http package, turning JSON into Dart classes, FutureBuilder and StreamBuilder, and sinks and streams.

Working with APIs and Asynchronous Operations

These days, most applications communicate with services on the internet in some way or another. This generally happens by communicating with the service's API, or Application Programming Interface, via HTTP(s) communications.

Since we have no control over how long that communication may take, we need to build our applications in such a way that the application is not blocked from further interaction and processing while we wait for a response. We do this by a method called asynchronous programming. In this chapter, we will delve into asynchronous programming and learn how to communicate with APIs.

Companion code: the publisher's repository holds this chapter's code as Example 7.1–Example 7.28 in the Chapter 07 folder; from Example 7.15 on, each example is the whole app up to that point, so each code block below is labelled with the first example that contains it. The repository has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).

Chapter overview

Structure

  • Welcome to the Future
  • Requesting data from an API
  • Classifying API responses
  • Sending data to an API
  • Flutter's asynchronous widgets
  • Sinks and streams

Objectives

After completing this chapter, you will have a fundamental understanding of concurrency in programming. You will know the difference between synchronous and asynchronous operations and how each style of code can impact the performance of your application. Furthermore, you will learn what APIs are and how to interact with them. Additionally, you will learn about data streams and how to use them in your code. Finally, you will use this knowledge to build a simple application that streams data from an API to build a list in Flutter, and then you will learn how to create new items on that list by sending data to the API and listening for a response.

Runnable example

The chapter's album app (both the FutureBuilder and the StreamController version) and its pure-Dart examples are also available as a runnable project with tests in examples/flutter_for_jobseekers_ch07/. The code on this page is shown as the book prints it, with conversion glitches fixed.

Welcome to the Future

To understand asynchronous operations, the first concept we need to learn about is Futures. As the name suggests, a Future is something that occurs in the future. It is a promise that something will eventually happen.

Synchronous code

Let us start by writing some synchronous code to see what that looks like and how it functions:

Example 7.1 · Example 7.1.dart
import 'dart:convert';
import 'dart:io';

void main() {
  final String fileContents = _readFileSynchronously('my_file.json');
  final Map<String, dynamic> jsonData = jsonDecode(fileContents);

  print('The first value is: ${jsonData.values.first}');
}

String _readFileSynchronously(String filename) {
  final File file = File(filename);
  final String contents = file.readAsStringSync();
  return contents.trim();
}

Runnable copy: examples/flutter_for_jobseekers_ch07/bin/read_file_sync.dart (reads the example's my_file.json)

This code will read the contents of a JSON file, decode it, and print out the first value.

The ${jsonData.values.first} is using what we call String interpolation. String interpolation will always return a string, even if the variable is null, in which case the string it returns is simply null. That is because the variable has the .toString() method called on it, which will usually return the string null when the value is, indeed, null.This can be used to get the contents of a variable, like we are doing here, but any code that's in between the braces will also be run. It is not entirely uncommon to run one or more methods within string interpolation, but do keep in mind that, if abused, this could lead to your code becoming less readable. Anyway, let us get back to analyzing this code.
The problem with this block of code is that the application stops processing everything until the file has been read in, in its entirety. If you have got a very large file, this would mean the application would simply stop responding until the entire file has been read into memory. Clearly, this is not ideal.

Asynchronous code

So, let us take the same code and update it to read the file asynchronously:

Example 7.2 · Example 7.2.dart
import 'dart:convert';
import 'dart:io';

void main() async {
  final String fileContents = await _readFileAsynchronously('my_file.json');
  final Map<String, dynamic> jsonData = jsonDecode(fileContents);

  print('The first value is: ${jsonData.values.first}');
}

Future<String> _readFileAsynchronously(String filename) async {
  final File file = File(filename);
  final String contents = await file.readAsString();
  return contents.trim();
}

Runnable copy: examples/flutter_for_jobseekers_ch07/bin/read_file_async.dart

Note the changes throughout the file:

Keywords

The async and await keywords have been added.

Asynchronous method

The method called on the file has been updated to use the asynchronous version.

Return type

The return type of the method is now a Future.

When you mark a method as async, it will immediately return a Future when invoked while using the await keyword. This suspends execution of the code within the function until the Future that is returned by readAsString() completes. Once readAsString() has finished its work, the function will resume processing until it encounters a return statement, which completes the function by returning a Future<String>, where the string is the value returned from the readAsString() method. This allows the application to continue processing even as the file is being read into memory.

Using .then()

Let us look at another example. Consider the following code:

Example 7.3 · Example 7.3.dart
String? hello = await Future<String?>.delayed(const Duration(seconds: 1)).then((_) => "Hello");

In this example, we have foregone calling a function that is explicitly marked as async, but we are still waiting for a return value. Can you see how the variable hello will only be set to the string "Hello" after the Future.delayed() completes? We are calling a Future directly and using the .then() method to get the value. This code will be synchronous, meaning that the rest of the application will pause execution until it completes the Future. This contrasts with the way we called a function marked with the async keyword before. The async/await method simulates the .then() way of completing the Future but is not blocking.

Corrected: this line does not block the application either. It uses await, so it can only run inside an async function, and await behaves the same whether the Future comes from an async function or from .then(): "The await expression makes execution pause until that object is available" (Dart, n.d.-a). Only the enclosing function pauses; the event loop keeps running other code, such as event handlers (Dart, n.d.-b). Code blocks only when it calls a synchronous API, such as readAsStringSync() above.

Also in this example, the Future is obvious as a Future and it will only take a single second for that Future to complete. Not all futures will always appear to be of the type Future (although we now know better, since we realize that all future functions return a Future and can, once the future has been resolved, be cast into the eventual final type we are expecting), nor will most futures complete in such a specific amount of time.

Think back to the first example, where we read in the contents of the file. The file.readAsString() method returned a Future, but it certainly did not explicitly say so, nor did we have any control over how long the process would take to complete.

Now that we have a basic understanding of asynchronous operations, futures, and the async/await keywords, let us look at the http package and learn how to use it to make an API call.

Requesting data from an API

An API works a lot like ordering food from a restaurant. You give your order to a waiter, who disappears for a little while before bringing the food you ordered back to your table. You have no idea how long it will take to get that food, who cooked it or how it was prepared, or where any of the ingredients came from. APIs are, in this regard, very similar. You approach the API with a request, then wait for a response, and you have no idea what happened on the server between those two actions.

To communicate with the API, we will first need an HTTP client which will do the communication on our behalf. The http package will suffice, but there are other, more powerful HTTP clients (such as Dio) out there if you find yourself running into the limitations of http. The http package comes with a multitude of classes, and the two we are going to focus on right now are Client and Response.

Client is the HTTP client itself, used to communicate with APIs or make other network calls, such as downloading a file. There are a couple of different ways that people invoke a Client object.

Importing with a namespace

Some will import the http package using a namespace like http, which looks like the following:

Example 7.4 · Example 7.4.dart
import 'package:http/http.dart' as http;

Then, they use it to make requests with http.get(…). This is a valid way of working with the package, but it does mean that every class that the http package provides will need to be referenced by a preceding http., such as http.Response. This can make the code a bit harder to work with in some instances. However, there are some advantages to using namespaces, as well:

Avoid naming conflicts
advantage
By using a namespace, you can avoid naming conflicts between different packages or libraries that you are importing. Since each package has its own namespace, you can use the same variable or class name from different packages without any conflicts.
Better readability
advantage
When you use a namespace, it makes your code more readable and organized. It allows you to group related classes, functions, and constants together under a common name, which makes it easier to understand the purpose of each import.
Faster compilation
advantage
When you use a namespace, it can improve the compilation time of your code. This is because the compiler can optimize the imports by only including the necessary code from each package, instead of importing the entire package.
Easier code maintenance
advantage
Using a namespace can make it easier to maintain your code in the long run. If you need to update a package, you can simply update the import statement without having to change all the references to that package throughout your codebase.
Better code reusability
advantage
When you use a namespace, it allows you to reuse the same code across different projects without any conflicts. Since each package has its own namespace, it can be easily included in different projects without any issues.
Corrected: a prefix does not make compilation faster. The Dart documentation gives one reason for it: "If you import two libraries that have conflicting identifiers, then you can specify a prefix for one or both libraries" (Dart, n.d.-c), and it says nothing about compilation time. A prefixed import brings in the same library as an unprefixed one; only the way you refer to its names changes.

Instantiating a Client per call

Another way is by simply importing http, then using Client().get(…), where you instantiate the class and use it in the same line. No longer would you have to prefix each of the classes with the library name, however this can also become confusing.

If you are authenticating to the API by using HTTP headers, you will have to add those headers each time you make a request, instead of having a single HTTP client which remembers those headers. Not to mention the fact that instantiating a new Client for each call is horribly inefficient.
For these reasons, it is recommended to go with a hybrid solution: import http normally, then create a Client variable, which you can use to make your HTTP calls.

Let us put this into action with a quick example:

Example 7.5 · Example 7.5.dart
import 'dart:convert';
import 'package:http/http.dart';

Client http = Client();

void main() async {
  final Response response = await fetchAlbum();
  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print('The album title is: ${data["title"]}');
  }
}

Future<Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

This code will fetch some data from an API, then print out a piece of it. There is a lot of room for improvement, though. For starters, it only checks for an HTTP status code of 200 (OK) and has no error handling whatsoever.

Guard clauses

Instead of checking explicitly for a success state, we should instead check for the opposite:

Example 7.6 · Example 7.6.dart
void main() async {
  final Response response = await fetchAlbum();
  if (response.statusCode != 200) {
    print('There was an error fetching the album.');
    return;
  }

  final data = jsonDecode(response.body);
  print('The album title is: ${data["title"]}');
}

Client http = Client();

Future<Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/a'));
}

Note how the URI for the album to fetch has changed from a 1 to an a causing the API call to return a non-200 status code. We now check for that non-200 status code in the same way we were checking for a successful response before. If we receive any status code other than a 200, we print out our error message and then prevent the rest of the function from executing with the return statement.

By doing it this way, we are using a guard clause style of programming. That is, we know what code we want to run if everything goes well, so let us just check for all the things which could go wrong before running the happy-path code. This will reduce the number of errors we have to check for later in our code.

Classifying API responses

In our previous example, we referenced the data returned from the API when printing it out using data["title"]. This is not very robust, however. If the element lacks a title field, the code will break. Additionally, it does not give us a nice Dart object to work with. It is time we create our own class to handle this, but first we need to understand the structure of the data we are working with.

The structure of JSON

By printing out the response.body, we can see the JSON which is returned to us:

{userId: 1, id: 1, title: quidem molestiae enim}

JavaScript Object Notation (JSON) is a structured key-value way of representing data. Note that when we ask Dart to print out the JSON for us, it has stripped away the quotes which would normally be around any strings. A raw JSON response would look like the following:

{"userId": 1, "id": 1, title: "quidem molestiae enim"}
Corrected: this line is not valid JSON. In JSON every key is a double-quoted string, as "userId" and "id" are, so the raw response reads "title": "quidem molestiae enim".
Understanding the difference in how the data can be displayed is vital. See how in both examples the integers are unquoted? They are a different data type (int) than the other value (a String). Trying to access the integer as a string will throw an error in your code, thus why it is important to know how the JSON data is structured.

The Album class

Alright, now that we understand the structure of the data in the JSON response, we can create a class that we will eventually use to cast the response data into.

Example 7.7 · Example 7.7.dart
class Album {
  int? userId;
  int? id;
  String? title;

  Album({this.userId, this.id, this.title});

  factory Album.fromJson(Map<String, dynamic> json) => Album(
    userId: json["userId"],
    id: json["id"],
    title: json["title"],
  );
}

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/album.dart

We have made all the different fields nullable, since we cannot guarantee the response of the API, and we have no idea if all the fields will be returned. We also created a factory that we can call when creating our new Album class. The factory will take in the JSON data (as a Map<String, dynamic>) and return the Album object. See how we were able to map the JSON values to the corresponding Album parameters?

Returning an Album

Now that we have a class with parameters matching the JSON response, we can update our code to use it. First, let us fix the fetchAlbum method. Instead of returning a Response, we should return our Album. After all, it is not a fetchResponse method!

Example 7.8 · Example 7.8.dart
Future<Album?> fetchAlbum() async {
  final Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode != 200) {
    print('There was an error fetching the album.');
    return null;
  }

  final Map<String, dynamic> data = jsonDecode(response.body);
  final Album album = Album.fromJson(data);

  return album;
}

This is already much better. We moved the error handling from the main method into the fetchAlbum method, too. It makes more sense for that logic to be here, rather than in the main method, because this is where the HTTP call is being made and where the logic deciding whether to cast the resulting JSON into an Album is stored. This results in a much cleaner main method, by comparison:

Example 7.9 · Example 7.9.dart
void main() async {
  final Album? album = await fetchAlbum();
  print('The album title is: ${album?.title ?? "Undefined"}');
}

Also, take note of the line where we turn the data into an Album using our new fromJson method. If we wanted, we could check some parameters in the Album before returning it, such as making sure the title is not null. In this instance, we are just going to return whatever we end up with.

Another way of handling this would be to specify defaults in the Album's fromJson method. For example, you could use json["title"] ?? "Undefined" and mark the title as no longer nullable. That might not work in every situation, though, so instead we are simply checking for the title when we print it out and handling the error state there. There is one other method we can use to handle errors like this, which we will look at in the next section.

Passing in the ID

There is one more thing we can do to improve the fetchAlbum method, though. Since we know that the API references a given album by its integer ID, we can pass in that integer ID to the fetchAlbum method when we call it. This would result in a much more reusable piece of code, instead of the method only ever returning a single, given album. Here is what that might look like:

Example 7.10 · Example 7.10.dart
void main() async {
  final Album? album = await fetchAlbum(id: 1);
  print('The album title is: ${album?.title ?? "Undefined"}');
}

Future<Album?> fetchAlbum({required int id}) async {
  final Response response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'));

  if (response.statusCode != 200) {
    print('There was an error fetching the album.');
    return null;
  }

  final Map<String, dynamic> data = jsonDecode(response.body);
  final Album album = Album.fromJson(data);

  return album;
}

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/album_api.dart (fetchAlbum, shared by the scripts and the app)

Now that we are passing in an ID to the method, we can leverage this flexibility to grab a whole bunch of albums:

Example 7.11 · Example 7.11.dart
void main() async {
  final List<int> albumsToFetch = [1, 2, 3];
  for (final int albumToFetch in albumsToFetch) {
    final Album? album = await fetchAlbum(id: albumToFetch);
    print("Album ${album?.id}'s title is: ${album?.title ?? 'Undefined'}");
  }
}

Runnable copy: examples/flutter_for_jobseekers_ch07/bin/fetch_albums.dart

Sending data to an API

Now that we know how to receive data from an API, it is time to talk about sending data to an API. We will expand our previous example to include a createAlbum method that we can call. This method will tell the API to create an album with a given title:

Example 7.12 · Example 7.12.dart
Future<Album> createAlbum(String title) async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
        'title': title,
    }),
  );

  if (response.statusCode != 201) {
    throw Exception('Failed to create album.');
  }

  return Album.fromJson(jsonDecode(response.body));
}

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/album_api.dart (createAlbum)

Here, we are using http.post rather than http.get to send data to the API. The structure is a bit different when we are doing a POST instead of a GET:

Headers

We need to specify the headers, so the API knows what type of data we are sending over. In this instance, we tell it that we are sending JSON data that has been encoded using UTF-8.

Body

We must specify a body of the HTTP request that includes a JSON object with the data we are sending to the API. The body starts out as a Map, and then we use jsonEncode from the dart:convert package to convert it to a JSON string. The <String, String> tells us what type of data the Map has for its keys and values. If you were sending a mix of strings, integers, lists, and so on, you would use <String, dynamic>, instead.

URI

Once the data has been converted to a JSON object, the last thing which differs is the URI to which we send the request. If you recall, in the previous example, our HTTP GET specified an ID for the album. In this instance, since we are creating a new album, we have not been assigned an ID yet. For this reason, we omit the ID from the URI, and once the API request has been completed, the resulting data which is returned will have our brand-new ID.

Not all APIs are made equal, and it is important to note that. This method of creating and retrieving data is common, but far from the only way for APIs to be designed. It is important to check with the documentation of the API that you are working with to understand what URIs to use for the different create, read, update, and delete (CRUD) operations and what format the data should be sent in. To read the documentation of the example API we have been using, head over to https://jsonplaceholder.typicode.com/.

To run our code and create an album, it is as simple as the following:

Example 7.13 · Example 7.13.dart
void main() async {
  final Album album = await createAlbum("My own album");
  print("Album ${album.id}'s title is: ${album.title}");
}
JSONPlaceholder only pretends to store the album: "The resource is not really created on the server, but the response is faked as if" (JSONPlaceholder, n.d.). Every new album comes back with the ID 101, and fetching that ID afterwards finds nothing. (Added, not in the book.)

Throwing instead of returning null

Look back at the createAlbum method for a minute. Remember how we handled error cases in the fetchAlbum method? The createAlbum method uses a different way of handling those error cases. This time, we are checking for the HTTP status code 201 (Created) and in the instance that we do not receive a successful response, we throw an Exception, rather than making our return value nullable.

This is an ideal way to handle errors, as we can use other built-in logic to catch those errors.
Example 7.14 · Example 7.14.dart
void main() async {
  try {
    final Album album = await createAlbum("My own album");
    print("Album ${album.id}'s title is: ${album.title}");
  } catch (e) {
    print("There was an exception: $e");
  }
}

Runnable copy: examples/flutter_for_jobseekers_ch07/bin/create_album.dart

As you can see, sending data to an API is just as easy as retrieving data from the API. These examples are all in pure Dart code, however. Let us see how these examples might be used in the context of a Flutter application.

Flutter's asynchronous widgets

We need some basic boilerplate code to display a Flutter UI that we can work with; otherwise, we are just going to keep both the fetchAlbum and createAlbum methods, and the Album class:

Example 7.15 · Example 7.15.dart
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Albums'),
        ),
        body: AlbumList(),
      ),
    );
  }
}

class AlbumList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Text('TODO: Fetch and display a list of albums');
  }
}
Corrected:primarySwatch no longer colors the app. ThemeData.useMaterial3 "is true by default" (Flutter, n.d.-a), and with Material 3 the theme's colorScheme defaults to the Material 3 baseline scheme, which primarySwatch does not feed into. To get a blue color scheme, use ThemeData(colorSchemeSeed: Colors.blue), as the runnable copy does.

FutureBuilder

With our boilerplate code in place, let us first look at how to fetch the albums and display them. For this, we are going to use a pair of widgets: FutureBuilder and ListView. We are also going to need to create a method that will let us fetch all the albums in a range of integers:

Example 7.16 · Example 7.16.dart
Future<List<Album>> fetchAlbums() async {
  final List<int> albumsToFetch = List<int>.generate(20, (i) => i + 1);
  final List<Album> albums = [];

  for (final int albumToFetch in albumsToFetch) {
    final Album? album = await fetchAlbum(id: albumToFetch);
    if (album != null) albums.add(album);
  }
  return albums;
}

You may notice some code in there that you do not yet recognize: the List.generate method. By giving it an integer (in this example, 20), it runs a method that many times and performs some action. The second parameter, (i), assigns the value of the current list index to the variable i, then returns a value of i+1 and adds it to the list. This is repeated until the process has run for the number of iterations specified. The result is a list of integers ranging from 1 to 20. This is the list of albums that we will be fetching for our eventual list.

Extra credit: how could you expand this to get the next page of results, albums 21-40?

Now that we have got a method that will fetch a given number of albums, we need a widget that will run that method for us. This is where FutureBuilder comes into play. FutureBuilder has two parameters:

future
Future
Takes in the object that returns a future, which in our case will be the fetchAlbums method.
builder
method
Will return a widget and has access to the FutureBuilder's AsyncSnapshot data as well as the current BuildContext. The AsyncSnapshot has some very useful information that we will use to decide what widget to display to the user.

Let us look at all this in action:

Example 7.17 · Example 7.17.dart
class AlbumList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchAlbums(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        if (snapshot.connectionState == ConnectionState.done &&
          snapshot.hasData) {
          return const Text("Done loading data");
        }
        return const Text("There was a problem loading the album list.");
      },
    );
  }
}

We are mostly interested in the builder method right now, as the rest is self-explanatory.

Waiting

The first check will return a CircularProgressIndicator while we are waiting for the Future to complete.

Done

The second check will return the widget we want to display once the Future has successfully completed.

Anything else

If neither of those states can be satisfied (such as in the case where the connection times out, there is no data returned, and so on), an error message will be shown to the user.

Remember, the builder must always return a widget, which is why we have a guard at the bottom that returns an error message.
Corrected:fetchAlbums() should not be called inside build. "The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. ... If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted" (Flutter, n.d.-b). As printed, every rebuild fetches all 20 albums again. The runnable copy makes AlbumList a StatefulWidget that starts the future once in initState.

ListView

At this point, we have a widget which is calling the API, retrieves the list of albums, and handles the waiting and error states. Next, we need to replace the placeholder text with a list of the album titles that were received. We are going to do this with the ListView widget.

Example 7.18 · Example 7.18.dart
if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
  final List<Album> albums = snapshot.data;
  return ListView.builder(
    itemCount: albums.length,
    itemBuilder: (BuildContext context, int index) => ListTile(
      title: Text(albums[index].title ?? "Undefined"),
    ),
  );
}
ListView.builder is a magical little widget. It builds a scrollable list and only builds the exact number of widgets that can be displayed on the screen. For this reason, it is highly performant with very long lists, especially in contrast to something like a Column, which builds all its children all the time, even when they are not on screen.

By specifying an itemCount, the ListView.builder knows precisely how many items it will have to build. It uses that information to iterate through the itemBuilder method, passing the current index of the item it is building as a parameter. We can use that index to grab the corresponding item from our list, which we do with albums[index] in this example. The result is that a scrollable, performant list of the album titles is generated automatically for us.

We chose to use a ListTile to display the title of the album, but any widget will do. Try swapping the ListTile for a Card widget for some added dimension to the resulting list. The title parameter will need to be swapped for a child parameter, and the content will benefit from some extra padding, like the following:

Example 7.19 · Example 7.19.dart
if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
  final List<Album> albums = snapshot.data;
  return ListView.builder(
    itemCount: albums.length,
    itemBuilder: (BuildContext context, int index) => Card(
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Text(albums[index].title ?? "Undefined"),
      ),
    ),
  );
}

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/future_builder/main_future.dart (the whole FutureBuilder version; run it with flutter run -t lib/future_builder/main_future.dart)

Adding a FloatingActionButton

Now that we can display a list of albums, we should add a way for us to create an album. Let us add a FloatingActionButton to our Scaffold, so we can add an album from anywhere. However, to properly pass the BuildContext into the onPressed method, we will want to break out the Scaffold into its own widget, which we will call Home:

Example 7.20 · Example 7.20.dart
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Albums'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // TODO: Implement dialog to get an album title, then create the album
        },
        child: const Icon(Icons.add),
      ),
      body: const AlbumList(),
    );
  }
}

Showing a dialog

Flutter offers a showDialog method for us to display a popup where we can collect information from the user. This is an asynchronous method that will display a Dialog over the UI and can return some sort of value, if desired. It takes in a BuildContext and uses that context in its builder method. The builder method returns the Dialog itself. We can leverage this system to create a popup that asks the user to enter the name of an album.

Let us start by building the helper method that will show the Dialog and return the value:

Example 7.21 · Example 7.21.dart
Future<String?> _userInputDialog(BuildContext context) async {
  return await showDialog<String>(
    context: context,
    builder: (BuildContext context) {
      return SimpleDialog(
        title: const Text('Create Album'),
        contentPadding: const EdgeInsets.all(24),
        children: [
          TextFormField(
            decoration: const InputDecoration(
              hintText: "Album name",
            ),
            onFieldSubmitted: (String? value) {
              Navigator.pop(context, value);
            },
          ),
        ],
      );
    },
  );
}

This simple Dialog will have a title and a text input. We are using a SimpleDialog, which is a subclass of the Dialog. It provides us with the necessary options we need, but there are other types of Dialogs you could use, such as the AlertDialog for example.

Submit

For the user to submit their input, they simply need to press the Enter key on the keyboard once they are finished.

Cancel

To cancel or dismiss the dialog, they can tap or click anywhere outside of the dialog.

With our helper function in place, we only need to hook it up to the onPressed method of our FloatingActionButton:

Example 7.22 · Example 7.22.dart
class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Albums'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final String? title = await _userInputDialog(context);
          if (title == null) {
            throw Exception('Cancelled Album creation.');
          }

          if (title.isNotEmpty) {
            final Album album = await createAlbum(title);
            print("Created new album! ${album.title}");
          }
        },
        child: const Icon(Icons.add),
      ),
      body: const AlbumList(),
    );
  }
}

Since we made our onPressed method an async, we can await the return value of the Dialog as a nullable String (remember, the user can always cancel.) After a quick check to make sure the title is not empty, we can await our createAlbum method with the new title, returning a newly created Album. Finally, we print the album details out to prove that it was, indeed, created.

The only problem is that the new album is not added to the list. For that, we are going to need to talk about streams.

Sinks and streams

Sibling to the async/await operators is the async*/yield operators. Let us look at an analogy to understand the relationship between these concepts.

async / await — filling a glass

Let us suppose that you are thirsty and would like a glass of water. You pick up the glass, fill it with water, and once it is full you take a drink. You can do other things while you are waiting for the glass to fill, but you cannot take a drink until it is full. This is async (you can do other things while you wait for the glass to fill) and await (you must wait for the glass to fill completely before taking a drink).

async* / yield — drinking through a straw

Now, suppose you want to drink from the glass while it is being filled. Not only that, but you have got a button you can push that will add lemonade into the stream of water. Each time you press the button, a bit of lemonade is added to the stream. Refreshing! To take a drink while your glass is being filled, you grab a straw and start sucking on it while the water fills the glass. Then, you decide to push the button to add some lemonade to the mix. This is async* (the act of filling the glass does not block you from consuming the beverage) and yield (pushing the button adds more things into the stream in a process called a sink, which is then emitted, or yielded, from the stream).

In our previous example, our ListView.builder used the data from the FutureBuilder to compile a list of Albums, which it then used to build the individual Cards displaying the album titles. We displayed a CircularProgressIndicator while the albums were being fetched from the API, which prevented us from showing any album until they were all loaded.

Furthermore, once the fetchAlbums method has completed, the list of albums is finalized, meaning we cannot add anything new to it without fetching everything all over again. So much for adding our newly created album to the list.

The StreamController

Clearly, we are going to need a different approach to accomplish what we want here. Let us refactor our code to use sinks and streams. The first thing we will need to do is pull in the dart:async library to get access to the StreamController widget. This widget will allow us to control our stream. After we have imported the library, we can go ahead and create a new StreamController:

Example 7.23 · Example 7.23.dart
import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart';

void main() => runApp(const MyApp());
Client http = Client();
final StreamController streamController = StreamController();
...
Corrected:StreamController is not a widget. It is a plain Dart class from dart:async, "A controller with the stream it controls" (Dart, n.d.-d); the widget in this section is StreamBuilder.

We will use this StreamController to add our events to the stream's sink and to listen to whatever streams back out. Let us start by reworking the fetchAlbums method to use the new StreamController:

  • Since we are going to be sending a sink event instead of returning a value, our return type becomes void.
  • We still need the async keyword because we will be awaiting each album as we fetch it from the API, though.
  • The other major change is that we no longer keep track of all the Albums that come back from the API. Instead, we pass each of them off to the StreamController to deal with. This means we no longer need our List<Album> variable, and we can remove the return statement.
  • In place of those, we will take the album we get back and add an event to the StreamController's sink:
Example 7.23 · Example 7.23.dart
void fetchAlbums() async {
  final List<int> albumsToFetch = List<int>.generate(10, (k) => k + 1);

  for (final int albumToFetch in albumsToFetch) {
    final Album? album = await fetchAlbum(id: albumToFetch);
    streamController.sink.add(album);
  }
}

The async* alternative

Note that we could technically add the event directly to the StreamController, too. This way, however, we are being more verbose for the sake of education. If we were not concerned about adding new events to our sink later, we could forego the StreamController entirely. Instead, we would opt for a return value of Stream<Album> and use the async* keyword. Then, instead of adding an event to the StreamController's sink, we would yield the album. That code would look like the following:

Example 7.25 · Example 7.25.dart
Stream<Album> fetchAlbums() async* {
  final List<int> albumsToFetch = List<int>.generate(10, (k) => k + 1);

  for (final int albumToFetch in albumsToFetch) {
    final Album? album = await fetchAlbum(id: albumToFetch);
    yield album;
  }
}

Companion code: Example 7.25 declares Stream<Album?> instead, so it also yields the albums that were not found (null).

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/album_generator.dart

Corrected: this does not compile. album is an Album?, and a Stream<Album> can only yield an Album. Yield only the albums that were found: if (album != null) yield album;, as the runnable copy does.

At that point, we would not care about the StreamController at all, so we could simply subscribe to fetchAlbums as a stream. However, since we know that we eventually want to create a new album and add it to the stream, it is better to use the StreamController in this instance.

StreamBuilder

The next thing we need to do is update the AlbumList widget. Previously, we were using a FutureBuilder widget and calling the fetchAlbums method to get the data we needed to build the list. Since fetchAlbums no longer returns a list of albums, this will not work for us anymore. Instead, we will use the StreamBuilder widget to accomplish the task, and instead of a future parameter, we have a stream parameter.

Where does the stream come from, you ask? The answer lies within our StreamController. By specifying streamController.stream as the stream to use, any data emitted from the StreamController will be used to build the list.

We are not quite done yet, though. The ListView.builder still wants a list of items to use to build itself. Before, that list was provided directly by the fetchAlbums method. Now, we no longer have a list — we just have a stream of items. We are going to have to build and maintain our own list. We will prefix the variable with an underscore, just to remind ourselves that we are only using it within the context of this single widget, and we should not be trying to access it from anywhere else. We will also want to place it outside our build method, so it does not get reinitialized to an empty list each time the widget rebuilds:

Example 7.26 · Example 7.26.dart
...
final List<Album> _albums = [];

@override
Widget build(BuildContext context) {
  ...

We will also want to convert our StatelessWidget into a StatefulWidget, so we can start the stream when the widget is initialized. Finally, we want to change the way we handle the incoming data. Instead of assigning snapshot.data to the albums variable, we want to add that snapshot.data (which is now a single Album) to our new list of albums, _albums. We can also remove our CircularProgressIndicator and clean up the logic which tests the connection state, since we no longer care what the connection state is and only if there is new data to add:

Example 7.27 · Example 7.27.dart
class AlbumList extends StatefulWidget {
  const AlbumList({super.key});

  @override
  _AlbumListState createState() => _AlbumListState();
}

class _AlbumListState extends State<AlbumList> {
  final List<Album> _albums = [];

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: streamController.stream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          _albums.add(snapshot.data);
        }
        return ListView.builder(
          shrinkWrap: true,
          itemCount: _albums.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(8),
                child: Text(_albums[index].title ?? "Undefined"),
              ),
            );
          },
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    fetchAlbums();
  }
}
Corrected: the builder is the wrong place to add to _albums. The builder "is called at the discretion of the Flutter pipeline, and will thus receive a timing-dependent sub-sequence of the snapshots" (Flutter, n.d.-c). So every rebuild that is not caused by a new event (a hot reload, a parent rebuild) adds the last album again, and albums that arrive within the same frame are skipped. The runnable copy adds each album exactly once, when the stream emits it (streamController.stream.map(...), created once in initState), and the builder only reads the list.

Now, if you run the code, you will see the individual albums stream into the list, one by one.

Adding the new album to the stream

There is just one last thing we must do: when we create a new album, we need to add it to the list. Fortunately, this is the exact same process that we use in the fetchAlbums method. In our Home widget, once we have created the new album, we simply add an event to the StreamController:

Example 7.28 · Example 7.28.dart
class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Albums'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final String? title = await _userInputDialog(context);
          if (title == null) {
            throw Exception('Cancelled Album creation.');
          }

          if (title.isNotEmpty) {
            final Album album = await createAlbum(title);
            streamController.sink.add(album);
          }
        },
        child: const Icon(Icons.add),
      ),
      body: const AlbumList(),
    );
  }
}

Runnable copy: examples/flutter_for_jobseekers_ch07/lib/main.dart (the whole StreamController app; cancelling the dialog returns instead of throwing an uncaught exception)

Now, whenever you create a new album, it will be added to the bottom of the list, automatically!

Conclusion

Congratulations on making it through this chapter. Some of the content we covered here was relatively complex. We learned all about concurrency, including the async/await keywords, async*/yield keywords, and using a StreamController to add an event to the sink and listen to the objects being emitted from the stream, along with their corresponding widgets. We also learned both how to receive data from and send data to an API. Then, we learned how to convert the raw data we received from the API into a Dart object that we care about.

Armed with this knowledge, you will have all the tools you need to build dynamic applications that leverage the power of APIs — opening a whole new world of possibilities! What will you build first? Maybe a weather app?

In the upcoming chapter, we are going to explore just what exactly we were doing when we invoked Navigator.pop() in our Dialog. In fact, we will take an in-depth look at what exactly Navigator is, how it works, and what its shortcomings are. Then, we will look at the newer API that unlocks even more potential, and finally we will explore a package that helps make our life easier when we are working with navigation and routing. See you over there!

Questions

  1. What is a Future?
  2. What is the difference between synchronous code and asynchronous code?
  3. What happens to the application when there is a long-lived, synchronous task being executed?
  4. What are the async and await keywords used for?
  5. What type of value does an asynchronous operation return?
  6. What is an API?
  7. What package(s) can be used to communicate with an API?
  8. What sort of data is generally returned from an API?
  9. What is an HTTP status code, and what are some common ones?
  10. What is a guard clause?
  11. What is JSON, and what are some considerations which are important to consider when working with JSON data?
  12. When communicating with an API using an HTTP client, a "verb" is used to determine which kind of action the client should take. The verbs POST and GET are used for which types of operations? Extra credit: What about PUT, PATCH, and DELETE?
  13. When sending a POST request to an API, which properties are required to be passed into the request?
  14. What does CRUD mean?
  15. What HTTP verbs relate to which CRUD operations?
  16. How can you generate List<int> containing all the odd numbers from 27 to 99?
  17. How can you tell if a FutureBuilder has completed its future?
  18. Why would somebody choose to use a ListView over a Column? Why would somebody choose to use a Column over a ListView?
  19. How do you display a dialog to a user?
  20. Given a dialog with two options, yes and no, how do you return either true or false from the dialog?
  21. What is a sink? What is a stream?
  22. What are the async* and yield operators used for?
  23. What is the async* equivalent to a FutureBuilder?
  24. What library provides widgets which are used with sinks and streams?
  25. How do you add an event to a sink?

Key terms

Application Programming Interface (API)
A connection between two pieces of software to exchange information.
async
Dart's async keyword is used to mark a method as having a return type of Future<T>.
async*
Dart's async* keyword is used to mark a method as having a return value of Stream<T>.
Asynchronous operations
Code that executes in parallel, neither blocking the other.
await
Dart's await command is used to wait for the execution of an asynchronous operation to complete its future. The await keyword must exist within an asynchronous method or widget which expects a future.
Future
A promise given by an asynchronous operation to return a value when it has finished processing.
JSON
JavaScript Object Notation. A key/value pair-based textual representation of data. JSON is commonly used when sending data to and receiving data from APIs.
String interpolation
Code that is executed whenever a String is evaluated during a widget build or method call. A null string being interpolated will return the string "null" while methods being called will run at the time that the string is evaluated. Code that is interpolated is contained within ${} in a string.
Synchronous operations
Code that executes one after the other. The next line cannot execute until the previous has finished, which is blocking.
yield
Dart's yield keyword is used inside an async* method to add an item to the stream.
Corrected: asynchronous Dart code does not run in parallel. An isolate has "a single thread running an event loop"; Future and Stream code takes turns on that one thread, and only separate isolates "enable parallel code execution on multiple processor cores" (Dart, n.d.-b). Asynchronous operations are concurrent: while one waits, for example on file I/O, other code runs.

Further reading

JSON and serialization

Learn more about JSON and serialization.

HTTP response status codes

HTTP status codes and their meanings.

References

Copyright © 2026