Flutter Stream.periodic

Created At: 2022-12-09 21:04:11 Updated At: 2022-12-10 01:33:04

Flutter Stream.periodic, periodic timer, flutter stream subscription, cancel and listen

We will learn about flutter stream.periodic and how to cancel and subscribe. We will create stream of events using Stream.periodic and then subscribe it to StreamSubscription.

Continuous events would be emitted from Stream.periodic and then we will that event to our app. This event would be integer type.

So it would more like counter or timer app where every one second later, we see the changes in value.

You may ask, how do we create a source of events?

  final Stream _myStream =
  Stream.periodic(const Duration(seconds: 1), (int count) {
    return count;
  });

The above code creates source of events or streams of events. Every one second later, it returns a count value. An integer value.

This source of events we subscribe to StreamSubscription object _sub

    _sub = _myStream.listen((event) {
      setState(() {
        _computationCount=event;
        // Set the background color to a random color
        _bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      });
    });

With _sub it's subscribed. We would also use _sub.cancel() to cancel the subscription.

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,

      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final Stream _myStream =
  Stream.periodic(const Duration(seconds: 1), (int count) {
    return count;
  });

  late StreamSubscription _sub;
  int _computationCount = 0;

  Color _bgColor = Colors.indigo;

  @override
  void initState() {
    _sub = _myStream.listen((event) {
      setState(() {
        _computationCount=event;
        // Set the background color to a random color
        _bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _bgColor,
      appBar: AppBar(
        title: const Text('Stream'),
        backgroundColor: Colors.transparent,
      ),
      body: Center(
        child: Text(
          _computationCount.toString(),
          style: const TextStyle(fontSize: 150, color: Colors.blue),
        ),
      ),
      // This button is used to unsubscribe the stream listener
      floatingActionButton: FloatingActionButton(
        child: const Icon(
          Icons.stop,
          size: 30,
        ),
        onPressed: () => _sub.cancel(),
      ),
    );
  }
  @override
  void dispose() {
    _sub.cancel();
    super.dispose();
  }

}

Learn more about

StreamBuilder vs FutureBuilder

Comment

Add Reviews