StreamBuilder - Flutter

In This post we are going to learn StreamBuilder in flutter

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<String> subscription;

  var streamController = StreamController<String>();

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

  Stream<String> 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<String>(
            stream: streamData,
            builder: (BuildContext context, AsyncSnapshot<String> 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 Flutter