Exploring StreamBuilder in Flutter: Building Reactive UIs
10 June, 2023
0
0
0
Contributors
Introduction
In modern app development, real-time data has become increasingly prevalent. To efficiently handle and display such dynamic information, Flutter provides the StreamBuilder widget. StreamBuilder is a powerful tool that allows developers to build reactive user interfaces that automatically update as new data streams in. In this blog post, we will delve into the world of StreamBuilder and explore how it can elevate your Flutter app's responsiveness.
Understanding StreamBuilder
StreamBuilder is a widget provided by Flutter that takes a stream as input and rebuilds its child tree whenever new data is emitted from the stream. It effectively separates the UI layer from the data layer, allowing for a clear separation of concerns and enabling real-time updates without excessive manual intervention.
Example Usage:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:liquid_swipe/liquid_swipe.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stream Builder Demo',
debugShowCheckedModeBanner: false,
home: StreamBuilderDemo(),
);
}
}
class StreamBuilderDemo extends StatefulWidget {
const StreamBuilderDemo({super.key});
@override
State<StreamBuilderDemo> createState() => _StreamBuilderDemoState();
}
class _StreamBuilderDemoState extends State<StreamBuilderDemo> {
late StreamController<int> _streamController;
@override
void initState() {
_streamController = StreamController<int>();
super.initState();
Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_streamController.sink.add(timer.tick);
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StreamBuilderDemo Example'),
),
body: Center(
child: StreamBuilder<int>(
stream: _streamController.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
'Current number: ${snapshot.data}',
style: TextStyle(fontSize: 24),
);
} else {
return CircularProgressIndicator();
}
},
),
),
);
}
@override
void dispose() {
_streamController.close();
super.dispose();
}
}
This code demonstrates the usage of the StreamBuilder
widget in Flutter. Let's go through it step by step:
- The code starts with the standard
main()
function, where theMyApp
widget is instantiated and run. MyApp
is a stateless widget that serves as the root of the application. It sets the title and the home screen as an instance of theStreamBuilderDemo
widget.StreamBuilderDemo
is a stateful widget that extendsState<StreamBuilderDemo>
. It represents the main widget where theStreamBuilder
is used.- Inside the
_StreamBuilderDemoState
class, aStreamController<int>
called_streamController
is declared. This controller will be used to manage the stream. - In the
initState()
method, the_streamController
is initialized, and aTimer.periodic
is used to emit numbers to the stream every second. ThesetState()
function is used to update the UI and trigger a rebuild with the latest number. - The
build()
method is overridden to create the UI. It displays anAppBar
and aCenter
widget containing theStreamBuilder
. TheStreamBuilder
listens to the stream from_streamController.stream
. - Inside the
builder
function of theStreamBuilder
, it checks if the snapshot has data. If data is available, it displays the current number using aText
widget. If no data is available, it shows aCircularProgressIndicator
to indicate that data is still loading. - The
dispose()
method is overridden to properly close the_streamController
when the widget is disposed to avoid memory leaks.
Overall, this code sets up a StreamBuilder
that listens to a stream created by a StreamController
. The stream emits numbers every second, and the UI automatically updates to display the latest number in real-time.
Output
Here's the output of the above code 👇
Conclusion
StreamBuilder is an essential widget in the Flutter framework that enables the creation of reactive user interfaces by automatically updating the UI in response to data streams. By harnessing the power of streams, developers can effortlessly handle real-time data updates and provide users with a seamless experience. With its intuitive usage and flexibility, StreamBuilder is an invaluable tool for building dynamic and responsive Flutter applications.
Incorporating StreamBuilder into your projects empowers you to build robust, real-time features that keep your app's content fresh and engaging. So why not leverage StreamBuilder to handle dynamic data streams and provide your users with an immersive and up-to-date experience in your Flutter applications?
For more amazing readings, follow me on Showwcase and Twitter 😃
flutter
developer
ui
statemanagement
app