StreamBuilder - Flutter

In This post we are going to learn StreamBuilder in flutter

 

The Stream builder needs mainly 3 parameters: stream, builder, and initialData. The initial is used as a dummy or empty element to act as the first element.

The builder method receives context and snapshot of the stream.

We can use stream.connectionState to find the status of the stream,

We can use stream.hasData ad stream.data to build widget when the widget is build.

We can also use stream.hasError to build when an Error occurs

 

Let's start

Step 1: Create Flutter Application

Step 2: Create dart file and update below code

 
import 'dart:async';

import 'package:flutter/material.dart';

class StreamBuilderWidget extends StatelessWidget{
  var index = 0;
  StreamSubscription subscription;

  var streamController = StreamController();

  //To Emit the stream
  StreamSink get streamSink  => streamController.sink;

  Stream get streamData => streamController.stream;

  StreamBuilderWidgetState()
  {
    streamSink.add("0");
  }



  void onFloatActionButtonPress() {

    streamSink.add(index.toString());
    index++;
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("Stream Builder"),
        backgroundColor: Colors.pink,),
      body: Center(
        child:  StreamBuilder(
            stream: streamData,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              return Text('Result: ${snapshot.data}');
            }
        )
      ),
        floatingActionButton: FloatingActionButton(
            onPressed: onFloatActionButtonPress,
            child: Icon(Icons.add))

    );

  }

}
 

 

Step 3: Update main dart file with below code

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.pink
      ),
      home: StreamBuilderWidget(),
    );
  }

}

 

Step 4: Run application

StreamBuilder