StreamBuilder is similar to FutureBuilder, provides the ability to acquire asynchronous data and update ui
Stream is an event stream, which is similar to RxJava. It allows us to emit an event from one end and listen to changes in the event from the other end. Through Stream we can design reactive code based on event flow on Flutter logic
Stream is not flutter widget, it provided by Dart
Stream is an abstract interface
StreamBuilder Constructor
const StreamBuilder({ Key key, this.initialData, Stream<T> stream, @required this.builder, }) |
Example
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)) ); } } |