Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Stream.periodic In Flutter

Streams are more uncommon than futures, yet they are similarly as helpful. For those new to streams, it is a strategy to deal with the flow of data from input to output. They are like futures in the manner that they are both asynchronous. This implies we don’t need to wait for them while they do their tasks. The thing that matters is that overall: Streams execute tasks ordinarily; Futures execute operations once.

In this blog, we will explore the Stream. periodic In Flutter. We will see how to implement a demo program and we will see how to use Stream. periodic in your flutter applications.

Stream. periodic constructor — Stream class — dart: async library — Dart API
Creates a stream that repeatedly emits events at period intervals. The event values are computed by invoking…api. flutter.dev

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The Stream. periodic constructor, as its name suggests, is utilized to make a stream that communicates events more than once at period intervals. The event esteems are computed by invoking computation. The contention to this callback is a whole number that beginnings with 0 and is increased for each event.

Demo Module ::

The above demo video shows how to use Stream. periodic in a flutter. It shows how Stream. periodic will work in your flutter applications. It shows when the app we are going to build has a background color that changes over time. It also displays an increasing number in the center of the screen. We can stop these relentless behaviors by pressing the floating button. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

First, we will create a final Stream and add a variable that is _myStream is equal to the Stream. periodic in bracket Duration was second is 1, int count and return count.

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

Now subscription on events from _myStream

late StreamSubscription _sub

The number will be displayed in the center of the screen. It changes over time

int _computationCount = 0;

Background color. In the beginning, it’s blueGrey but it will be a random color later

Color _bgColor = Colors.blueGrey;

Create a initState() method. In this method, we will add variable _sub is equal to _myStream.listen{}. In bracket, we will add setState() method. In this method, we will _computationCount is equal to the event. Also, we will set the background color to a random color.

@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();
}

We will create a dispose method. In this method, cancel the stream listener on dispose. Add _sub .cancel()

@override
void dispose() {
_sub.cancel();
super.dispose();
}

In the body, we will add the Center() widget. In this widget, we will add Text _computationCount.toString().

Center(
child: Text(
_computationCount.toString(),
style: TextStyle(fontSize: 150, color: Colors.white),
),
),

Then we will create a FloatingActionButton(). This button is used to unsubscribe the stream listener. When the user press a button, the stream listener was canceled. We will add the background color was red. It’s child property, we will add an Icons. stop. Also, we will add onPressed was _sub. cancel().

floatingActionButton: FloatingActionButton(
backgroundColor: Colors.red,
child: Icon(
Icons.stop,
size: 30,
),
onPressed: () => _sub.cancel(),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File:

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';
import 'package:flutter_stream_periodic_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

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.blueGrey;

@override
void initState() {
_sub = _myStream.listen((event) {
setState(() {
_computationCount = event;

_bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
});
});
super.initState();
}

@override
void dispose() {
_sub.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _bgColor,
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Flutter Stream.periodic Demo'),
backgroundColor: Colors.white12,
),
body: Center(
child: Text(
_computationCount.toString(),
style: TextStyle(fontSize: 150, color: Colors.white),
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.red,
child: Icon(
Icons.stop,
size: 30,
),
onPressed: () => _sub.cancel(),
),
);
}

}

Conclusion:

In the article, I have explained the basic structure of Stream. periodic in a flutter; you can modify this code according to your choice. This was a small introduction to Stream. periodic On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Stream. periodic in your flutter projects. We will show you what Introduction is?. Make a demo program for working Stream. periodic. In this blog, we have examined the Stream. periodic of the flutter app. I hope this blog will help you in the comprehension of the Stream. periodic in a better way. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.