Stream Provider

on Thursday, 6th of August, 2020

StreamProvider provides, well, Streamed values. Like FutureProvider, provided values will be auto-magically passed the new values of the provided value as they come in. The major difference is that the values will trigger a re-build as many times as it needs to.

If you need a refresher on Streams, I recommend you check out my code-cartoon of Dart Streams, or find a whole chapter about Streams in my book Flutter in Action. Streams can be hard to grasp (and implement) if you aren't familiar, but they're wildly useful and popular in the Flutter ecosystem.

StreamProviders work so similarly to FutureProvider, that we should just jump straight into code. First, setting up the stream:

class Person {
  Person({this.name, this.initialAge});

  final String name;
  final int initialAge;

  // A StreamProvider's only requirement is that, well,
  // you give it a stream value.
  // This [generator] function will _yield_ a new number every second.
  Stream<String> get age async* {
    var i = initialAge;
    while (i < 85) {
      await Future.delayed(Duration(seconds: 1), () {
        i++;
      });
      yield i.toString();
    }
  }
}

Live Example



Join thousands of Flutter developers.

Sign up for infrequent updates about Flutter and Dart.

You can get all this content and more in one place. Check out my new book Flutter in Action