StreamBuilder Widget – Flutter Widget Guide By Flutter Agency

· 6 min read
StreamBuilder Widget - Flutter Widget Guide By Flutter Agency
StreamBuilder Widget - Flutter Widget Guide By Flutter Agency

Earlier we have been through How to make Count Query in a Firebase where we have learned about StreamBuilder Widget so now this is time to get into a detailed article on the same.

Are you excited to explore yourself with StreamBuilder Widget?

So let’s get into the same Step by Step.

What is StreamBuilder Widget in Flutter ?

StreamBuilder Widget is a StatefulWidget that responds to the asynchronous procession of data. In other words, we can say that it is able to keep a ‘running summary’ and or record and note the ‘latest data item’ from a stream of data.

Basically it will have two parameters.

  • Stream,
  • Builder,

What is Stream in Flutter?

As per the official document Stream will have a definition like below

” A Stream provides a way to receive a sequence of events. Each event is either a data event, also called an element of the stream, or an error event, which is a notification that something has failed. When a stream has emitted all its events, a single “done” event will notify the listener that the end has been reached ”

In simple words, we can say that Stream is like a pipe where users can put a value on one end and Listener on the other end the Listener will receive that value. A Steam can also have multiple listeners and all listeners can have the same values when you put it into a pipe.

There are two kinds of streams :

  • Single Subscription: There could be a maximum of one listener to this stream.
  • Broadcast: There could be the infinite number of the listener to this stream.

What is Builder in Flutter?

Builder is basically used to convert Stream of data into Widgets.

The Default constructor of StreamBuilder Widget looks like below:

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

In the above constructor, all fields marked with @required must not be empty. Now let’s understand each property in detail.

Properties:

  • Key key: This attribute key controls how one widget replaces another widget in the tree.
  • T initialData: This attribute is the data that will be used to create the initial snapshot. Providing this value (presumably obtained synchronously somehow when the Stream was created) ensures that the first frame will show useful data. Otherwise, the first frame will be built with the value null, regardless of whether a value is available on the stream: since streams are asynchronous, no events from the stream can be obtained before the initial build.
  • AsyncWidgetBuilder<T> builder: This attribute specifies a build strategy that is currently used by this builder. It should always return widget and should not have any side effects as it will be called multiple times.
  • Stream<T> stream: The asynchronous computation to which this builder is currently connected, possibly null. When changed, the current summary is updated using afterDisconnected, if the previous stream was not null, followed by afterConnected, if the new stream is not null.

How to use StreamBuilder Widget in Flutter?

Consider the following code snippet to understand how to use it in a Flutter.

In order to use first, we will create a Stateful Widget and define a counter and controller using a below snippet.

int _counter = 0;
StreamController<int> _events;

initState() will look like below:

  @override
initState() {
  super.initState();
  _events = new StreamController<int>();
  _events.add(0);
}

Create a _incrementCounter() like below:

void _incrementCounter() {
    _counter++;
    _events.add(_counter);
  
}

We will get data using the below code snippet:

snapshot.data,

StreamBuilder Widget will look like below:

StreamBuilder(
             stream: _events.stream,
             builder: (BuildContext context, snapshot) {
               return new Text(
                 snapshot.data.toString(),
                 style: Theme.of(context).textTheme.caption.copyWith(
                   fontSize: 18,
                   fontWeight: FontWeight.w600
                 ),
               );
             },
           ),

FloatingActionButton will look like below:

floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add,),
      )

The complete Source Code will look like below.

import 'dart:async';

import 'package:flutter/material.dart';

class StreamBuilderWidget extends StatefulWidget {

  @override
  _StreamBuilderWidgetState createState() => _StreamBuilderWidgetState();
}

class _StreamBuilderWidgetState extends State<StreamBuilderWidget> {
  int _counter = 0;
  StreamController<int> _events;

    @override
  initState() {
    super.initState();
    _events = new StreamController<int>();
    _events.add(0);
  }

  void _incrementCounter() {
      _counter++;
      _events.add(_counter);
    
  }
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body:Center(
       child: new Column(
         mainAxisAlignment: MainAxisAlignment.center,
         children: <Widget>[
           new Text(
             'You have pushed the button this many times:',
           ),
           StreamBuilder(
             stream: _events.stream,
             builder: (BuildContext context, snapshot) {
               return new Text(
                 snapshot.data.toString(),
                 style: Theme.of(context).textTheme.caption.copyWith(
                   fontSize: 18,
                   fontWeight: FontWeight.w600
                 ),
               );
             },
           ),
         ],
       ),
        ),
        floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add,),
      )
       
    );
  }
}


Conclusion:

In this article, we have been through What is StreamBuilder Widget and how to use it in a Flutter.

That’s it for today.

Still, need support for Flutter Development? We Would love to help you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply