Chapter 9. Async Dart and Flutter and infinite scrolling

 

This chapter covers

  • Futures in Dart
  • Streams and sinks in Dart
  • Async builder in Flutter
  • Slivers and scrollable widgets
  • Scroll physics

This chapter could contain the most difficult concepts to wrap your head around, unless you’re familiar with async UI programming. The beginning of this chapter is only about asynchronous concepts and implementing them in Dart. After that, I examine how those concepts are useful in Flutter.

Note

If you’re okay with the following code listing, then you should skip to section 9.2, where we begin the Flutter portion.

Listing 9.1. Example Dart code using streams and sinks
// Streams and Sinks
StreamController<bool> _controller = StreamController<bool>();
Stream get onEvent => _controller.stream;
 
void handleEvent() {
    onEvent.listen((val) => print(val));
}
 
// async / await
void getRequest() async {
    var response = await http.get(url);
    return response;
}

If you aren’t comfortable with this listing, then strap in. Async programming is mandatory in modern UIs, but it can be difficult to grok at first.

Dart programming makes heavy use of a specific async pattern, which is known in many languages as observables. (Observables are also the foundational concept of Rx libraries.) In Dart, observables are called streams. You won’t get very far into any Dart code before you have to start dealing with streams. And, in fact, I’d claim they’re necessary for effective Flutter programming.

9.1. Async Dart

9.1.1. Future recap

9.1.2. The async/await keywords

9.1.3. Catching errors with futures

9.1.4. Catching errors with try and catch

9.2. Sinks and streams (and StreamControllers)

9.2.1. Anatomy of the observer pattern with Dart streams

9.2.2. Implementing streams

9.2.3. Broadcasting streams

9.2.4. Higher-order streams

9.3. Using streams in blocs

9.3.1. Blocs use inputs and outputs

9.3.2. Implementing a bloc input

9.4. Async Flutter: StreamBuilder

9.5. Infinite and custom scrollable widgets

9.5.1. CustomScrollView and slivers

9.5.2. Catalog widget scroll view

9.5.3. The SliverGrid widget

9.5.4. Delegates

9.5.5. Custom slivers

sitemap