Junior — Middle
Can you give an example of using StreamBuilder component for real-time interface updates?
sobes.tech AI
Answer from AI
The StreamBuilder component in Flutter is used to build an interface that updates in real-time when new data arrives from a stream. For example, if you have a stream of numbers that emits a new value every second, StreamBuilder will automatically update the widget with this number.
Example:
Stream<int> counter() async* {
int i = 0;
while (true) {
await Future.delayed(Duration(seconds: 1));
yield i++;
}
}
class CounterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: counter(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('Counter: \\${snapshot.data}');
} else {
return CircularProgressIndicator();
}
},
);
}
}
In this example, the text on the screen will update every second, showing the current value of the counter.