What is StreamBuilder?
- Flutter course
- Intermediate
- Lesson 26/99
- 4 min
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.
Practice 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ı').
Starter code
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(
// akış dinleyici widget ekle
child: Text('bekle'),
),
);
}
}Sample 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');
},
),
),
);
}
}Expected output
ekran açıldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which parameter takes the Stream to watch in StreamBuilder?
- stream Correct answer
- child
- future
- builder
Explanation: StreamBuilder's stream parameter takes the Stream to watch; builder produces a widget on every new value.
2 Bind StreamBuilder's stream parameter
StreamBuilder<String>(
____: sayacStream,
builder: (context, snapshot) {
return Text(snapshot.data ?? '0');
},
)
StreamBuilder<String>(
stream: sayacStream,
builder: (context, snapshot) {
return Text(snapshot.data ?? '0');
},
)
Explanation: StreamBuilder's stream parameter takes the Stream to watch; builder produces a widget on every new value.
3 StreamBuilder parts
| Term | Meaning |
|---|---|
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 |