Working with APIs and Asynchronous Operations
Working with APIs and Asynchronous Operations
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.
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
Runnable example
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:
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.
${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.Asynchronous code
So, let us take the same code and update it to read the file asynchronously:
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
async and await keywords have been added.Asynchronous method
Return type
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:
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.
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.
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
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:
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:
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.
Client for each call is horribly inefficient.The recommended hybrid
Client variable, which you can use to make your HTTP calls.Let us put this into action with a quick example:
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:
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.
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"}
"userId" and "id" are, so the raw response reads "title": "quidem molestiae enim".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.
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!
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:
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.
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:
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:
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:
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.
To run our code and create an album, it is as simple as the following:
void main() async {
final Album album = await createAlbum("My own album");
print("Album ${album.id}'s title is: ${album.title}");
}
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.
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:
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');
}
}
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:
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.
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:
fetchAlbums method.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:
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.
builder must always return a widget, which is why we have a guard at the bottom that returns an error message.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.
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:
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:
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:
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
Cancel
With our helper function in place, we only need to hook it up to the onPressed method of our FloatingActionButton:
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.
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
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
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.
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:
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();
...
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
asynckeyword because we will beawaiting 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 theStreamControllerto deal with. This means we no longer need ourList<Album>variable, and we can remove thereturnstatement. - In place of those, we will take the album we get back and add an event to the
StreamController's sink:
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:
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
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.
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:
...
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:
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();
}
}
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:
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)
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.
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
- What is a
Future? - What is the difference between synchronous code and asynchronous code?
- What happens to the application when there is a long-lived, synchronous task being executed?
- What are the
asyncandawaitkeywords used for? - What type of value does an asynchronous operation return?
- What is an API?
- What package(s) can be used to communicate with an API?
- What sort of data is generally returned from an API?
- What is an HTTP status code, and what are some common ones?
- What is a guard clause?
- What is JSON, and what are some considerations which are important to consider when working with JSON data?
- 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
POSTandGETare used for which types of operations? Extra credit: What aboutPUT,PATCH, andDELETE? - When sending a POST request to an API, which properties are required to be passed into the request?
- What does CRUD mean?
- What HTTP verbs relate to which CRUD operations?
- How can you generate
List<int>containing all the odd numbers from 27 to 99? - How can you tell if a
FutureBuilderhas completed its future? - Why would somebody choose to use a
ListViewover aColumn? Why would somebody choose to use aColumnover aListView? - How do you display a dialog to a user?
- Given a dialog with two options, yes and no, how do you return either
trueorfalsefrom the dialog? - What is a sink? What is a stream?
- What are the
async*andyieldoperators used for? - What is the
async*equivalent to aFutureBuilder? - What library provides widgets which are used with sinks and streams?
- How do you add an event to a sink?
Key terms
Future<T>.async* keyword is used to mark a method as having a return value of Stream<T>.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.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.yield keyword is used inside an async* method to add an item to the stream.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
References
- BPB Publications. (n.d.). Flutter for Jobseekers (companion code repository). Retrieved from GitHub: https://github.com/bpbpublications/Flutter-for-Jobseekers (added, not in the book)
- Dart. (n.d.-a). Asynchronous programming. Retrieved from Dart: https://dart.dev/language/async (added, not in the book)
- Dart. (n.d.-b). Concurrency in Dart. Retrieved from Dart: https://dart.dev/language/concurrency (added, not in the book)
- Dart. (n.d.-c). Libraries & imports. Retrieved from Dart: https://dart.dev/language/libraries (added, not in the book)
- Dart. (n.d.-d). StreamController class. Retrieved from Dart API: https://api.dart.dev/dart-async/StreamController-class.html (added, not in the book)
- Flutter. (n.d.-a). useMaterial3 property. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/ThemeData/useMaterial3.html (added, not in the book)
- Flutter. (n.d.-b). FutureBuilder class. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html (added, not in the book)
- Flutter. (n.d.-c). StreamBuilder class. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html (added, not in the book)
- Flutter. (n.d.-d). JSON and serialization. Retrieved from Flutter: https://docs.flutter.dev/data-and-backend/serialization/json (added, not in the book)
- JSONPlaceholder. (n.d.). Guide. Retrieved from JSONPlaceholder: https://jsonplaceholder.typicode.com/guide/ (added, not in the book)
Using 3rd Party Libraries and External Assets
The pubspec.yaml file, adding images and fonts as assets, the Pub package ecosystem, judging package quality, playing audio with a package, and popular packages.
Navigation and Routing
Navigator 1.0 (push and pop, named routes, route arguments, returning data, Hero animations), the Router API (Navigator 2.0), and routing with Beamer.