Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Exploring StreamBuilder In Flutter

An asynchronous interaction might require an ideal opportunity to wrap up. Once in a while, there can be a few values emitted before the cycle wraps up. In Dart, you can make a capacity that returns a Stream, which can emanate a few values while the asynchronous process is active. Assuming you need to construct a widget in Flutter dependent on the snapshots of a Stream, there’s a widget called StreamBuilder.

In this blog, we will be Exploring StreamBuilder In Flutter. We will also implement a demo program and we show you how to use StreamBuilder in your flutter applications.

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introducton:

The StreamBuilder can listen to exposed streams and return widgets and catch snapshots of got stream information. The stream builder takes two contentions.

A stream

A Builder, which can change over components of the stream into widgets

The Stream resembles a line. At the point when you enter a value from one side and a listener from the opposite side, the listener will get that value. A stream can have various listeners and that load of listeners can get the pipeline, which will get equivalent value. How you put values on the stream is by utilizing the Stream Controller. A stream builder is a widget that can change over user-defined objects into a stream.

Constructor:

To utilize StreamBuilder, you need to call the constructor underneath:

const StreamBuilder({
Key? key,
Stream<T>? stream,
T? initialData,
required AsyncWidgetBuilder<T> builder,
})

Essentially, you need to make a Stream and pass it as the stream contention. Then, at that point, you need to pass an AsyncWidgetBuilder which can be utilized to construct the widget dependent on the snapshots of the Stream.

Parameters:

There are some parameters of StreamBuilderare:

  • Key? key: The widget’s key, used to control how a widget is supplanted with another widget.
  • Stream<T>? stream: A Stream whose snapshot can be gotten to by the builder function.
  • T? initialData: The data will be utilized to make the initial snapshot.
  • required AsyncWidgetBuilder<T> builder: The build procedure is utilized by this builder.

How to implement code in dart file :

You need to implement it in your code respectively:

Let’s create a Stream:

The following is a function that returns a Stream for generating numbers each one second. You need to utilize the async* keyword for making a Stream. To emit a value, you can utilize yield a keyword followed by the value to be emitted.

Stream<int> generateNumbers = (() async* {
await Future<void>.delayed(Duration(seconds: 2));

for (int i = 1; i <= 10; i++) {
await Future<void>.delayed(Duration(seconds: 1));
yield i;
}
})();

From that point onward, pass it as the stream argument

StreamBuilder<int>(
stream: generateNumbers,
// other arguments
)

Let’s create a AsyncWidgetBuilder

The constructor expects you to pass a named contention builder whose type is AsyncWidgetBuilder. It’s a function with two parameters whose types all together are BuildContext and AsyncSnapshot<T>. The subsequent boundary, which contains the current snapshot, can be utilized to figure out what ought to be rendered.

To make the function, you need to comprehend about AsyncSnapshot first. The AsyncSnapshot is an unchanging portrayal of the latest communication with an asynchronous computation. In this unique situation, it addresses the most recent communication with a Stream. You can get to the properties AsyncSnapshot to get the most recent snapshot of the Stream. One of the properties you might have to utilize is connectionState, an enum whose worth addresses the current association state to an asynchronous computation that is Steam in this unique circumstance.

StreamBuilder<int>(
stream: generateNumbers,
builder: (
BuildContext context,
AsyncSnapshot<int> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.active
|| snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.red, fontSize: 40)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),

AsyncSnapshot additionally has a property named hasError which can be utilized to check whether the snapshot contains a non-null error value. The hasError value will be valid if the most recent consequence of the asynchronous activity was failed. For getting to the information, first, you can check whether the snapshot contains information by getting to its hasData property which will be valid if the Stream has effectively discharged any non-null value. Then, at that point, you can get the information from the data property of AsyncSnapshot.

Because of the values of the properties above, you can figure out what ought to be rendered on the screen. In the code beneath, a CircularProgressIndicator is shown when the connectionState value is waiting. At the point when the connectionState changes to active or done, you can check whether the snapshot has an error or information. The builder function is called the circumspection of the Flutter pipeline. Thusly, it will get a timing-dependent sub-grouping of the snapshots. That implies in case there are a few values emitted by the Stream at practically a similar time, there’s plausible that a portion of the values is not passed to the builder.

The enum has some possible values:

  • > none: Not associated with any asynchronous computation. It can occur if the stream is null.
  • > waiting: Associated with an asynchronous computation and awaiting collaboration. In this context, it implies the Stream hasn’t been finished.
  • > active: Associated with an active asynchronous computation. For instance, if a Stream has returned any value yet is not finished at this point.
  • > done: Associated with an ended asynchronous computation. In this context, it implies the Stream has finished.

Let set the Initial Data:

You can alternatively pass a worth as the initialData argument which will be utilized until the Stream emits a emits. If the passed value isn’t null, the hasData property will be true at first in any event, when the connectionState is waiting

StreamBuilder<int>(
initialData: 0,
// other arguments
)

To show the initial data when the connectionState is waiting, the if snapshot.connectionState == ConnectionState.waiting then, block in the code above should be adjusted.

if (snapshot.connectionState == ConnectionState.waiting) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Visibility(
visible: snapshot.hasData,
child: Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.black, fontSize: 24),
),
),
],
);
}

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

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_steambuilder_demo/splash_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Splash(),
debugShowCheckedModeBanner: false,
);
}
}

Stream<int> generateNumbers = (() async* {
await Future<void>.delayed(Duration(seconds: 2));

for (int i = 1; i <= 10; i++) {
await Future<void>.delayed(Duration(seconds: 1));
yield i;
}
})();

class StreamBuilderDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _StreamBuilderDemoState ();
}
}

class _StreamBuilderDemoState extends State<StreamBuilderDemo> {

@override
initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter StreamBuilder Demo'),
),
body: SizedBox(
width: double.infinity,
child: Center(
child: StreamBuilder<int>(
stream: generateNumbers,
initialData: 0,
builder: (
BuildContext context,
AsyncSnapshot<int> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Visibility(
visible: snapshot.hasData,
child: Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.black, fontSize: 24),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.active
|| snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.red, fontSize: 40)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the StreamBuilder in a flutter; you can modify this code according to your choice. This was a small introduction to StreamBuilder 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 StreamBuilder in your flutter projects. We will show you what the Introduction is?. Show a constructor and parameters of Streambuilder. If you need to build a widget dependent on the result of a Stream, you can utilize the StreamBuilder widget. You can make a Stream and pass it as the stream contention. Then, at that point, you need to pass an AsyncWidgetBuilder work that is utilized to construct a widget dependent on the snapshots of the Stream. 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.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

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 *.