chapter nine

9 Async Dart and Flutter and Infinite Scrolling

 

In this chapter:

  • Futures in Dart
  • Streams and Sinks Dart
  • AsyncBuilder 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. If you’re okay with the the following code snippits, then you should skip to section 9.2

Listing 9.1. Example Dart code using Streams and Sinks
// Streams and Sinks
StreamController<bool> _controller = new 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 that, then strap in. Async programming is mandatory in modern UI, but it can be difficult to grok at first.

Dart programming makes heavy use of some specific async patterns, known in many languages as "observables". (Observables are also the base 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 say they’re necessary to effective Flutter programming.

9.1  Async Dart

9.1.1  Future Recap

9.1.2  async / await

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  The pieces of the observer patter

9.2.2  Implementing streams

9.2.3  Broadcast 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  CatalogWidget scroll view

9.5.3  Delegates