Flutter
What is StreamBuilder?
Bind a continuous data stream to UI with StreamBuilder.
What is StreamBuilder?
StreamBuilder is a widget that binds a Stream to the UI. The stream parameter takes the Stream to watch, and builder takes the function called on every new value.
StreamBuilder<String>(
stream: dataStream(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'empty');
},
)
Every new value from the Stream triggers the builder again.
Accessing data with snapshot
The builder function receives an AsyncSnapshot. On every new value from the Stream, snapshot.data updates and the builder is called again.
builder: (context, snapshot) {
return Text(snapshot.data ?? 'empty');
}
Build refreshes for every value until the Stream closes.
Exercise Display data with StreamBuilder
The veriAkisi async* method should yield 'Merhaba Stream'. In Ekrani stateless widget, display snapshot.data ?? '0' with StreamBuilder<String>. In main, call print('ekran açıldı').
Show example solution
import 'package:flutter/material.dart';
Stream<String> veriAkisi() async* {
yield 'Merhaba Stream';
}
void main() {
print('ekran açıldı');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<String>(
stream: veriAkisi(),
builder: (context, snapshot) {
return Text(snapshot.data ?? '0');
},
),
),
);
}
}
Test yourself
-
Which parameter takes the Stream to watch in StreamBuilder?
Show answer
stream — StreamBuilder's stream parameter takes the Stream to watch; builder produces a widget on every new value.
-
Bind StreamBuilder's stream parameter
StreamBuilder<String>(
____: sayacStream,
builder: (context, snapshot) {
return Text(snapshot.data ?? '0');
},
)
Show answer
StreamBuilder<String>(
stream: sayacStream,
builder: (context, snapshot) {
return Text(snapshot.data ?? '0');
},
)
-
StreamBuilder parts
- StreamBuilder
- Widget binding Stream to UI
- stream
- Parameter taking the Stream
- builder
- Function producing widget on each value
- snapshot
- Object carrying Stream's current state
Next lesson: What is a Stream?