Loading: 95 %

banner

Mastering Flutter Streams: Exploring Single and Broadcast Streams

14.12.23
Flutter

Introduction

Flutter, Google’s UI toolkit, is renowned for its expressive and flexible framework that allows developers to build natively compiled applications for mobile, web, and desktop from a single codebase. One powerful feature in Flutter is the use of streams, which enable efficient and asynchronous communication between different parts of your application. In this article, we’ll delve into the concept of streams in Flutter, specifically focusing on Single and Broadcast Streams. Additionally, we’ll explore the implementation of a custom stream function to deepen our understanding.

Overview of Streams in Flutter

Streams are a fundamental part of the Dart language, and Flutter leverages them to handle asynchronous programming. A stream is a sequence of asynchronous events, and it allows the components of your application to communicate without blocking the execution. Streams are crucial for handling user input, network requests, and other asynchronous tasks in a Flutter application.

In Dart, there are two types of streams: Single Subscription Streams and Broadcast Streams.

Single Subscription Streams

Single Subscription Streams allow only one listener to listen to the stream. Once a listener is subscribed, no other listeners can subscribe to the same stream. It is suitable for scenarios where you want to ensure that only one consumer is processing the stream events.


// main.dart

import 'dart:async';

void main() {
  // Creating a Single Subscription Stream
  StreamController<int> singleController = StreamController<int>();

  // Adding a listener to the stream
  StreamSubscription<int> subscription = singleController.stream.listen(
    (data) {
      print('Received: \$data');
    },
  );

  // Adding data to the stream
  singleController.add(1);
  singleController.add(2);
  singleController.add(3);

  // Closing the stream
  singleController.close();
}
        

Broadcast Streams

Broadcast Streams allow multiple listeners to subscribe to the same stream. This is useful when you want to broadcast events to multiple parts of your application simultaneously.


// main.dart

import 'dart:async';

void main() {
  // Creating a Broadcast Stream
  StreamController<int> broadcastController = StreamController<int>.broadcast();

  // Adding the first listener to the stream
  StreamSubscription<int> subscription1 = broadcastController.stream.listen(
    (data) {
      print('Listener 1 Received: \$data');
    },
  );

  // Adding the second listener to the stream
  StreamSubscription<int> subscription2 = broadcastController.stream.listen(
    (data) {
      print('Listener 2 Received: \$data');
    },
  );

  // Adding data to the stream
  broadcastController.add(1);
  broadcastController.add(2);
  broadcastController.add(3);

  // Closing the stream
  broadcastController.close();
}
        

Creating a Custom Stream Function

Now, let’s explore how to implement a custom stream function in Flutter. Suppose we want to create a stream that emits a sequence of Fibonacci numbers. We can achieve this by creating a custom stream function.


// main.dart

import 'dart:async';

// Custom Stream Function to generate Fibonacci numbers
Stream<int> generateFibonacci(int count) async* {
  int a = 0, b = 1;
  for (int i = 0; i < count; i++) {
    yield a;
    int temp = a + b;
    a = b;
    b = temp;
  }
}

void main() async {
  // Creating a custom stream for Fibonacci numbers
  Stream<int> fibonacciStream = generateFibonacci(5);

  // Listening to the custom stream
  await for (int value in fibonacciStream) {
    print('Fibonacci: \$value');
  }
}
        

Conclusion

Understanding streams in Flutter is crucial for developing responsive and efficient applications. By leveraging streams, developers can handle asynchronous events seamlessly. Additionally, creating custom stream functions allows for the implementation of tailored solutions to meet specific application requirements.

As you continue to explore Flutter, experimenting with streams will provide you with a powerful tool-set for building dynamic and interactive applications.

banner
avatar

Vishnu C Prasad

I'm Vishnu C Prasad, a Flutter Developer with a passion for crafting seamless and high-performance mobile applications. My journey in software development began with a deep interest in building digital solutions that make an impact. Over the years, I've honed my expertise in Flutter to create cross-platform mobile apps that are both visually appealing and functionally robust. With a solid foundation in modern development practices, I focus on delivering clean, maintainable code and exceptional user experiences.

I take pride in constantly learning and evolving with new technologies. My experience spans multiple projects, from personal endeavors like the Data Dex app, where I managed vehicle loan details, to collaborating on larger systems that solve real-world problems. I enjoy working on challenging projects and thrive in environments that allow me to innovate and push my skills further.

When I'm not coding, I love sharing my knowledge through blog posts and contributing to the developer community. I'm always open to new opportunities, whether it's freelance work, collaborations, or exciting roles in forward-thinking teams.

Let's connect and explore how we can bring your next project to life!

Work

06
  • 01. Brototype

    2022 - 2023

    As a Software developer at Brototype I Designed, developed, and maintained high-quality mobile applications for both iOS and Android platforms using Flutter & Collaborated with cross-functional teams to define, design, and ship new features

  • 02. Freelance Developer

    2023 - Present

    Designed, developed, and maintained high-quality mobile applications for both iOS and Android platforms using Flutter

Education

05
  • 01. Flutter development

    2024
    Certificate

    The Complete Flutter SDK, Flutter Framework, Dart guide to develop fast, production-grade apps for Android, iOS and Web

  • 02. React Development

    2021
    Certificate

    The Complete React Developer Course (w/ Hooks and Redux)

  • 03. Diploma in Computer Application (DCA)

    2019
    Certificate

    Diploma in Computer Application Graduation from LBS Centre for Science & Technology.

Skills

03
Flutter 90%
Flutter Bloc 90%
Nest.JS 75%
Express.JS 90%
Firebase 95%
React.JS 75%
Git 95%
HTML / CSS / JS 95%

Price

07
$ 19 /hour

Availability on a predetermined time

  • Prototyping and Wireframing
  • Website and App Development
Choose plan
$ 2900 /month

Full availability 8 hours a day

  • Prototyping and Wireframing
  • Website and App Development
  • Website Maintenance & Updates
Choose plan

Thank you very much for your attention ❤️ ! Follow me on social media and don't forget to visit my blog I post a lot of interesting things about development and not only.