Flutter Stream Tutorial — Asynchronous Dart Programming

Flutter Stream Tutorial — Asynchronous Dart Programming

In our last tutorial, we learned how to use asynchronous programming using Future in Flutter. Today we will learn how to do asynchronous programming using Stream.

To learn Dart programming language and Flutter framework check out my new course with a discount on Udemy: Mastering Dart Programming | For Flutter Developers

Stream is a sequence of asynchronous events. Unlike future a stream notify if there is an event is ready.

Some Notes:

  • Stream is similar like Future
  • Stream delivers zero or more than zero values or errors over time
  • To create Stream use StreamController class
  • By default, Stream is setup for single subscription. So two listen will not work.
  • For multiple listeners, use .asBroadcastStream() method

Let’s create a Stream of RandomNumber

import 'dart:async';
import 'dart:math' as Math;
class RandomNumber {
  final StreamController _controller = StreamController<int>();
  int _count = Math.Random().nextInt(100);
  int times = 0;
RandomNumber() {
    Timer.periodic(Duration(seconds: 1), (timer){
      _controller.sink.add(_count);
      _count = Math.Random().nextInt(100);
      times += 1;
if (times > 5) {
        timer.cancel();
        _controller.sink.close();
      }
    });
  }
Stream<int> get stream => _controller.stream;
}

Let’s create the main function to listen the change of stream:

void main() {
  final randomNumStream = RandomNumber().stream;
final subscription = randomNumStream.listen(
    (data){
      print('Data: $data');
    },
    onError: (err) {
      print('Error: $err');
    },
    cancelOnError: false,
    onDone: (){
      print('Done');
    }
  );
}

So if we run this program, we will see the output of a series of random numbers with a delay. So to put data in a stream, we can use StreamController‘s sink object to add data.

Finally, when we want to close the stream, we have to use sink object’s close method.

In the main function, we can use subscription object’s some other methods to pause, resume and close the stream listening.

One thing we have to remember, a listener can be used for one time. That means, if we want to use multi listener for same stream it will not work for the second listener. To do broadcasting for multi listener we can use broadcast method:

void main() {
  final broadCastRandomNumStream = RandomNumber().stream.asBroadcastStream();
final sub1 = broadCastRandomNumStream.listen(printData);
  final sub2 = broadCastRandomNumStream.listen(printData);
}
void printData(data){
  print('Data: $data');
}

On the other hand we can use generator function and yield keyword to put the values in the stream

import 'dart:io';
Stream<int> countStream(int max) async * {
  for (int i = 0; i < max; ++i) {
    yield i;
    sleep(Duration(seconds: 1));
  }
}
void main() {
  print('start');
  countStream(5).listen((data){
    print(data);
  },
  onDone: (){
    print("Done");
  });
  print('end');
}

Output

start
end
0
1
2
3
4
Done

Source: Thinkdiff.net

To view or add a comment, sign in

More articles by Mahmud Ahsan

Explore content categories