Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Types
  • Functions
  • Oops
  • Collections
  • Sets
  • Dart Interview Questions
  • Fluter
  • Android
  • Kotlin
  • Kotlin Android
  • Android with Java
  • Android Studio
Open In App
Next Article:
Flutter - FutureBuilder Widget
Next article icon

Flutter - StreamBuilder Widget

Last Updated : 16 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A StreamBuilder in Flutter is used to listen to a stream of data and rebuild its widget subtree whenever new data is emitted by the stream. It's commonly used for real-time updates, such as when working with streams of data from network requests, databases, or other asynchronous sources. In this article, we are going to see an example of a Streambuilder Widget by taking an Example.

Syntax of StreamBuilder

StreamBuilder<T>(
stream: yourStream, // The stream to listen to
initialData: initialData, // Optional initial data while waiting for the first event
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return YourLoadingWidget(); // Display a loading indicator while waiting for data
} else if (snapshot.hasError) {
return YourErrorWidget(error: snapshot.error); // Handle errors
} else if (!snapshot.hasData) {
return YourNoDataWidget(); // Handle the case when there's no data
} else {
return YourDataWidget(data: snapshot.data); // Display your UI with the data
}
},
)

Here we are going to see a simple example of a StreamBuilder in Flutter that listens to a stream of numbers and displays the latest number in real-time:

Required Tools

  • To build this app, you need the following items installed on your machine:
  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

A sample video is given below to get an idea about what we are going to do in this article.



Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'dart:async';
import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart
void main() {   runApp(MyApp()); } 

Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart
class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       debugShowCheckedModeBanner: false,       theme: ThemeData(         primarySwatch: Colors.green, // Set the app's primary theme color       ),       title: 'StreamBuilder Example',       home: NumberStreamPage(),     );   } } 

Step 5: Create NumberStreamPage Class

In this class we are going to Implement the StreamBuilder to display the numbers changes in real time.Here we are going to run a for loop from 0 to 9 and display the updates number by the help of StreamBuilder.Comments are added for better understanding.

StreamBuilder<int>(
stream: _numberStreamController.stream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Display a loading indicator when waiting for data.
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); // Display an error message if an error occurs.
} else if (!snapshot.hasData) {
return Text('No data available'); // Display a message when no data is available.
} else {
return Text(
'Latest Number: ${snapshot.data}',
style: TextStyle(fontSize: 24),
); // Display the latest number when data is available.
}
},
),
Dart
class _NumberStreamPageState extends State<NumberStreamPage> {   late StreamController<int> _numberStreamController;    @override   void initState() {     super.initState();      // Create a stream controller and add numbers to the stream.     _numberStreamController = StreamController<int>();     _startAddingNumbers(); // Start adding numbers to the stream.   }    void _startAddingNumbers() async {     for (int i = 0; i < 10; i++) {       await Future.delayed(Duration(seconds: 2)); // Delay for 2 seconds.       _numberStreamController.sink.add(i); // Add the number to the stream.     }   }    @override   void dispose() {     _numberStreamController.close(); // Close the stream when disposing.     super.dispose();   }    @override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(         title: Text('StreamBuilder Example'),       ),       body: Center(         child: StreamBuilder<int>(           stream: _numberStreamController.stream,           builder: (context, snapshot) {             if (snapshot.connectionState == ConnectionState.waiting) {               return CircularProgressIndicator(); // Display a loading indicator when waiting for data.             } else if (snapshot.hasError) {               return Text('Error: ${snapshot.error}'); // Display an error message if an error occurs.             } else if (!snapshot.hasData) {               return Text('No data available'); // Display a message when no data is available.             } else {               return Text(                 'Latest Number: ${snapshot.data}',                 style: TextStyle(fontSize: 24),               ); // Display the latest number when data is available.             }           },         ),       ),     );   } } 

Here is the full Code of main.dart file

Dart
import 'dart:async'; import 'package:flutter/material.dart';  void main() {   runApp(MyApp()); }  class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       debugShowCheckedModeBanner: false, // Remove the debug banner       theme: ThemeData(         primarySwatch: Colors.green, // Set the app's primary theme color to green       ),       title: 'StreamBuilder Example',       home: NumberStreamPage(),     );   } }  class NumberStreamPage extends StatefulWidget {   @override   _NumberStreamPageState createState() => _NumberStreamPageState(); }  class _NumberStreamPageState extends State<NumberStreamPage> {   late StreamController<int> _numberStreamController;    @override   void initState() {     super.initState();      // Create a stream controller and add numbers to the stream.     _numberStreamController = StreamController<int>();     _startAddingNumbers(); // Start adding numbers to the stream.   }    void _startAddingNumbers() async {     for (int i = 0; i < 10; i++) {       await Future.delayed(Duration(seconds: 2)); // Delay for 2 seconds.       _numberStreamController.sink.add(i); // Add the number to the stream.     }   }    @override   void dispose() {     _numberStreamController.close(); // Close the stream when disposing.     super.dispose();   }    @override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(         title: Text('StreamBuilder Example'),       ),       body: Center(         child: StreamBuilder<int>(           stream: _numberStreamController.stream,           builder: (context, snapshot) {             if (snapshot.connectionState == ConnectionState.waiting) {               return CircularProgressIndicator(); // Display a loading indicator when waiting for data.             } else if (snapshot.hasError) {               return Text('Error: ${snapshot.error}'); // Display an error message if an error occurs.             } else if (!snapshot.hasData) {               return Text('No data available'); // Display a message when no data is available.             } else {               return Text(                 'Latest Number: ${snapshot.data}',                 style: TextStyle(fontSize: 24),               ); // Display the latest number when data is available.             }           },         ),       ),     );   } } 

Output:


Next Article
Flutter - FutureBuilder Widget
author
chinmaya121221
Improve
Article Tags :
  • Dart
  • Flutter
  • Geeks Premier League
  • Flutter-Widgets
  • Geeks Premier League 2023

Similar Reads

  • Flutter - FutureBuilder Widget
    In Flutter, the FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a Future.  It is necessary for Future to be obtained earlier either through a change of state or change in dependencies. FutureBuilder is a Widget that will help you to execute some asynch
    4 min read
  • Flutter - LayoutBuilder Widget
    In Flutter, LayoutBuilder Widget is similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget's constraints. This is useful when the parent constrains the child's size and doesn't depend on the child's intrinsic size. The LayoutB
    3 min read
  • Flutter - TweenAnimationBuilder Widget
    In this article, we will learn about how to implement TweenAnimationBuilder Widget. Widget builder that animates a widget's property to a target value whenever the target value changes. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://me
    3 min read
  • Flutter - Stepper Widget
    In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. Stepper is generally used in filling forms online. For example, remember filling an online form for applying to any university or passport or driving license. We filled
    8 min read
  • Flutter - TabView Widget
    There are lots of apps where you often have come across tabs. Tabs are a common pattern in the apps. They are situated at top of the app below the App bar. So today we are going to create our own app with tabs. Table of Contents:Project SetupCodeConclusionProject Setup: You can either create a new p
    4 min read
  • Flutter - Stateful Widget
    A Stateful Widget has states in it. To understand a Stateful Widget, you need to have a clear understanding of widgets and state management. A state can be defined as "an imperative changing of the user interface," and a widget is "an immutable description of the part of the user interface". To lear
    4 min read
  • Flutter - ListTile Widget
    The ListTile widget is used to populate a ListView in Flutter. It contains a title as well as leading or trailing icons. Let's understand this with the help of an example. The Constructor of the ListTile classListTile({ Key key, Widget leading, Widget title, Widget subtitle, Widget trailing, bool is
    4 min read
  • Table Widget in Flutter
    Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. Th
    3 min read
  • Flutter - GridPaper Widget
    A grid paper is a paper that has a grid on it with divisions and subdivisions, for example, graph paper. We may use grid paper in creating the graphs in our flutter application. A sample image is given below to get an idea about what we are going to do in this article. How to use it?[GFGTABS] Dart G
    3 min read
  • Flutter - Stateless Widget
    Stateless Widget is something that does not have a state. To understand a Stateless Widget, you need to clearly understand widgets and states. A state can be defined as "an imperative changing of the user interface," and a widget is "an immutable description of the part of the user interface". To le
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences