hii I hope you all are well and doing something better in your life. so this time we understand what are StreamBuilder and FutureBuilder, how and when we use them.
Introduction
Flutter, the popular cross-platform framework, provides developers with two powerful widgets for handling asynchronous operations: StreamBuilder
and FutureBuilder
. Although they share similarities, it’s crucial to understand their differences to choose the appropriate one for your specific use case. In this blog post, we’ll dive into the characteristics and usage of both widgets, providing you with a comprehensive understanding of when to use each.
Introducing FutureBuilder
To begin, let’s explore FutureBuilder
, which is designed for handling asynchronous operations that return a single value in the future. Follow these steps to leverage the power of FutureBuilder
:
FutureBuilder
is used when you have a one-time asynchronous operation that returns a value, such as an HTTP request or reading from a file.- Import the required dependencies:
import 'dart:async';
. - Create a
Future
an object that represents the asynchronous operation you want to perform. For example, you can usehttp.get()
it to make an HTTP request and get a response. - Wrap the section of your UI that depends on the future result inside a
FutureBuilder
widget. - Pass the future object to the
FutureBuilder
using thefuture
parameter. - Implement the
builder
callback function of theFutureBuilder
widget. This function will be called when the future completes and returns a result. - Inside the
builder
function, access the snapshot of the future result usingsnapshot.data
. - Based on the state of the snapshot (
ConnectionState
andAsyncSnapshot
), you can handle different UI states such as data loading, error handling, or displaying the actual result. - Update your UI with the future result by accessing
snapshot.data
thebuilder
function.
you better understand the code so there it is.
open your main.dart file and implement this code and see the output of what is happening.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _count = 0; // used by StreamBuilder
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StreamBuilder VS FutureBuilder',style: TextStyle(fontSize: 18,color: Colors.black),),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildFutureBuilder(),
],
),
);
}
// constructing FutureBuilder
Widget _buildFutureBuilder() {
return Center(
child: FutureBuilder<int>(
future: _calculateSquare(10),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
return Text("Square = ${snapshot.data}",style: TextStyle(fontSize: 20,color: Colors.purple),);
return CircularProgressIndicator(color: Colors.green,);
},
),
);
}
// used by FutureBuilder
Future<int> _calculateSquare(int num) async {
await Future.delayed(Duration(seconds: 5));
return num * num;
}
}
Output:
Introducing StreamBuilder:
Moving on, let’s discuss StreamBuilder
, which is suitable for handling asynchronous operations that produce multiple values over time. Follow these steps to implement StreamBuilder
effectively:
StreamBuilder
is used when you have a stream of asynchronous data that can change over time, such as real-time updates from a database or web service.- Import the required dependencies:
import 'dart:async';
. - Create a
Stream
an object that represents the data stream you want to listen to. It could be an instance ofStreamController
, or you can use built-in streams likeStream.fromFuture
orStream.periodic
. - Wrap the section of your UI that depends on the stream data inside a
StreamBuilder
widget. - Pass the stream object to the
StreamBuilder
using thestream
parameter. - Implement the
builder
callback function of theStreamBuilder
widget. This function will be called whenever new data is emitted by the stream. - Inside the
builder
function, access the snapshot of the stream data usingsnapshot.data
. - Based on the state of the snapshot (
ConnectionState
), you can show different UI states such as data loading, error handling, or displaying the actual data. - Update your UI whenever the stream emits new data by accessing
snapshot.data
inside thebuilder
function.
Ok if you see the code then you better understand what I am saying
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _count = 0; // used by StreamBuilder
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StreamBuilder VS FutureBuilder',style: TextStyle(fontSize: 18,color: Colors.black),),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildStreamBuilder(),
],
),
);
}
// constructing StreamBuilder
Widget _buildStreamBuilder() {
return Center(
child: StreamBuilder<int>(
stream: _stopwatch(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active)
return Text("Stopwatch = ${snapshot.data}",style: TextStyle(fontSize: 20,color: Colors.orange),);
return CircularProgressIndicator();
},
),
);
}
// used by StreamBuilder
Stream<int> _stopwatch() async* {
while (true) {
await Future.delayed(Duration(seconds: 1));
yield _count++;
}
}
}
Output:
Conclusion:
In conclusion, both StreamBuilder
and FutureBuilder
are important widgets in Flutter for handling asynchronous operations and updating the UI based on the resulting data. Here’s a summary of their characteristics:
StreamBuilder:
- Used for continuous streams of data that can change over time.
- Suitable for real-time updates, such as database or web service changes.
- Requires an
Stream
object to listen to the data stream. - The
builder
the function is called whenever new data is emitted by the stream. - Allows you to handle different UI states based on the state of the stream (
ConnectionState
) and access the data usingsnapshot.data
.
FutureBuilder:
- Used for one-time asynchronous operations that return a value.
- Suitable for operations like HTTP requests or reading from files.
- Requires a
Future
object that represents the asynchronous operation. - The
builder
function is called when the future completes and returns a result. - Enables you to handle different UI states based on the state of the future (
ConnectionState
andAsyncSnapshot
) and access the result usingsnapshot.data
.
Both widgets serve similar purposes, but the key distinction lies in the nature of the asynchronous operations they handle. StreamBuilder
is used for continuous streams that can emit multiple data events over time, while FutureBuilder
is used for one-time operations that produce a single result.
Understanding when to use each widget is crucial for efficient and responsive Flutter app development. By leveraging the appropriate widget, you can effectively handle asynchronous data and provide a seamless user experience.
I hope now you understand what are StreamBuilder and FutureBuilder and why and where we use them.
❤️❤️ Thanks for reading this article ❤️❤️
If I got something wrong? Let me know in the comments. I would love to improve 🥰🥰🥰.
Clap 👏👏👏 If this article helps you.
if you like our work so please follow us on this Dosomthings
Our New and Attractive articles:
Tinder swipe card: How to implement tinder swipe card in a flutter.
Time Delay in Flutter: How to Run Code After Time Delay in Flutter App.
Flip/Rotate 3D Image: Flip/Rotate 3D Image Object By Drag Gestures Flipping Card.