A StreamBuilder is a widget in Flutter that builds itself based on the latest snapshot of interaction with a Stream. It’s a convenient way to handle real-time data and update the UI accordingly.
Properties:
- stream: The Stream that the builder will interact with.
- builder: A callback function that builds the widget based on the snapshot of the Stream.
- initialData: The initial data to be used before the stream emits any data.
How it works:
- The StreamBuilder widget is created with a Stream and a builder callback.
- The StreamBuilder interacts with the Stream and gets the latest snapshot.
- The builder callback is called with the snapshot, and it returns a widget based on the snapshot’s state.
- The StreamBuilder updates the UI with the widget returned by the builder callback.
Snapshot states:
- ConnectionState
.
none: The stream has not been initialized. - ConnectionState.waiting: The stream is waiting for the data.
- ConnectionState
.
active: The stream is active and has data. - ConnectionState
.
done: The stream has completed with data.
Example:
Dart
Stream<int> counterStream() async* {
int counter = 0;
while (true) {
await Future.delayed(Duration(seconds: 1));
yield counter++;
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: counterStream(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasData) {
return Center(child: Text('Counter: ${snapshot.data}'));
} else {
return Center(child: Text('Error'));
}
},
);
}
In this example, the StreamBuilder interacts with the counterStream stream and builds a widget based on the snapshot’s state. If the stream is waiting, it displays a CircularProgressIndicator. If the stream has data, it displays the counter value. If there’s an error, it displays an error message.
Key differences between FutureBuilder and StreamBuilder:
- FutureBuilder is used for one-time asynchronous operations, while StreamBuilder is used for real-time data streams.
- FutureBuilder has a single result, while StreamBuilder has multiple results over time.
CounterScreen StreamBuilder Example:
import 'package:flutter/material.dart';
// Screen that displays a counter using StreamBuilder
class CounterScreen extends StatelessWidget {
// A method that returns a Stream of integers, incrementing every second
Stream<int> counterStream() async* {
int counter = 0; // Initialize counter
while (true) {
await Future.delayed(Duration(seconds: 1)); // Wait for 1 second
yield counter++; // Emit the current counter value and increment it
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StreamBuilder Counter Example'), // AppBar title
),
body: Center(
// Use StreamBuilder to listen to the counterStream
child: StreamBuilder<int>(
stream: counterStream(), // Provide the stream to listen to
initialData: 0, // Set the initial value before the stream emits data
builder: (context, snapshot) {
// Snapshot contains the latest data and connection state
if (snapshot.connectionState == ConnectionState.waiting) {
// If the stream is waiting for data, show a loading indicator
return CircularProgressIndicator();
} else if (snapshot.hasError) {
// If there's an error, display an error message
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
// If the stream has data, display the current counter value
return Text(
'Counter: ${snapshot.data}',
style: TextStyle(fontSize: 24), // Text styling
);
} else {
// If there's no data, display a default message
return Text('No data available');
}
},
),
),
);
}
}
What’s up it’s me, I am aⅼso vіsiting this website daily,
this website is genuinely good and the uѕerѕ
aгe in fact sһaring fastidious thougһts.